Use unique_ptr for ownership and raw pointer otherwise?

I am C ++ 11 code. I have

class X { /* */ }; class A { std::vector<X*> va_x; }; class B { std::vector<X*> vb_x; std::vector<A> vb_a; }; 

X * s "va_x" inside my class A points to objects that X * s "vb_x" also points to inside my class B.

Now I would like to use smart pointers. It seems obvious to me that class B has ownership of the objects that X * points to (in particular, since my instances of A belong to B)

So I have to use unique_ptr for X inside B:

 class B { std::vector<unique_ptr<X>> vb_x; std::vector<A> vb_a; }; 

My question is: what should I do for class A? Should I keep the source pointers? So, in my unit tests, I have to admit that this leads to uncomfortable things (imo), for example (don't worry about encapsulation, it is not):

 unique_ptr<X> x(new X()); A a; a.va_x.push_back(&(*x)); //awkward, but what else can I do? A.vb_a.push_back(a); //ok B.vb_x.push_back(move(x)); //ok 
+7
source share
1 answer

You can use x.get() , which will return an internal pointer.

Also, yes, using source pointers to handle non-owner links is the way to go, see also this question .

+9
source

All Articles