STL vector and element constructors

J

Jan

Hi there,
I've created a reference to a new object (with private copy
constructor)
inside a STL vector

object& obj = aVector[aVector.size()+1]

Is there any possibility to define, which constructor for obj is used?
(In this case, obj() is called, but i want something like obj(xyz) )

Thanks,
Jan
 
A

Alf P. Steinbach

* Jan:
Hi there,
I've created a reference to a new object (with private copy
constructor)
inside a STL vector

Can't do that; standard collection elements must be copyable.

object& obj = aVector[aVector.size()+1]

Can't do that, either; figure out why (besides, there is a missing
semicolon).

Is there any possibility to define, which constructor for obj is used?

No constructor is used above.

(In this case, obj() is called, but i want something like obj(xyz) )

That's meaningless; please reformulate.
 
D

Dervish

Your code have a bug - it references non existent element. Operator []
does not create new element. Program can crush, constructor (any)
should no be called at all. To create new object using [] your should
use map.

To fix this using vector one can do smth like this:
aVector.resize(aVector.size()+1);
object& obj = aVector.back();
Is there any possibility to define, which constructor for obj is used?
No. The only was is to create custom class which calls proper ctor.
E.g.:
class ProperConstructObject : public object
{
public:
ProperConstructObject()
: object(xyz)
{

}
//...
};
Where xyz should be either global symbol or class member (may be
static).
 
B

benben

object& obj = aVector[aVector.size()+1]

The above does not create a new element for you. What the above does is
to give a new name to the second element following the last element. So
if aVector has 10 elements already, obj would be a new name for the 12th
element in aVector.

Ben
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top