dimanche 25 décembre 2016

Inserting element to container: copy constructor messes up pointers

My problem is that the default copy constr. messes up my pointers.

Simplified version:

  • I have a A class with the default copy constr.

  • A has 2 member objects: B and C.

  • B has a pointer to C.

Situation:

  • I store A in a std::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 A which has a B which has a pointer to the old A's C. Which doesn't exist anymore.

Simple solution would be:

  • In A there would be pointers to B and C

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?

Aucun commentaire:

Enregistrer un commentaire