My problem is that the default copy constr. messes up my pointers.
Simplified version:
I have a
Aclass with the default copy constr.Ahas 2 member objects:BandC.Bhas a pointer toC.
Situation:
I store
Ain astd::vector:vector.emplace_back(A(...));emplace_back does this:
Creating A (setting up B's pointer to C, etc)
Copying A into the vector. (default copy ctr: copies by value)
Destroying the "origin" A.
. Result:
- The storage has an
Awhich has aBwhich has a pointer to the old A's C. Which doesn't exist anymore.
Simple solution would be:
- In
Athere would be pointers toBandC
But this is not so good because why should A have pointers, when it owns its B and C and B and C shares lifetime with A.
Question:
Isn't there a better way than having pointers in A?
Or isn't there a simplier way than messing with copy constructor implementations?
I thought that emplace constructs "in-place", so why does it need a copy ctr?
Yes, there is. Furthermore, I don't see how having pointers in
Asolves the problem.A solution is to write a user defined copy constructor for
A, that will update the pointer of the copied member.No, a copy constructor is (perhaps arguably?) the simplest way to update the member pointer of the member.
It does.
It doesn't in general.
It does require either a move or copy constructor in this case, because you pass it a temporary object. The object in the vector is constructed "in-place", by using the move (or copy, if not movable) constructor with the temporary as the argument.
Instead, you could have passed the arguments of the constructor of
Adireclty toemplace_backso that no temporary is involved.Note that constructing the object in-place doesn't prevent the element of the vector from being copied, unless you have pre-reserved the memory so that no reallocation happens.