I have a case that I am not sure if I should use unique_ptr
or pass Object by values.
Say that I have class A which has a vector Of class B and Class C has a vector of class B as well. Every time I am adding a B Object to Vector in class C it should be Removed from vector of Class C and vice versa. When Object C is destroyed all the objects in B Vector class should be add to B vector in class A
class B {
public:
B();
virtual ~B();
};
class A {
C & c;
std::vector<B> bs;
public:
A(C & c ): c(c){};
virtual ~A();
void add(B b){
bs.push_back(b);
c.remove(b);
}
void remove(B b){
bs.erase(std::remove(bs.begin(), bs.end(), b), bs.end());
}
};
class C {
public:
A & a;
std::vector<B> bs;
C(A & a): a(a) {
};
virtual ~C(){
for (B b : bs) {
a.add(b);
remove(b);
}
}
void add(B b){
bs.push_back(b);
a.remove(b);
}
void remove(B b){
bs.erase(std::remove(bs.begin(), bs.end(), b), bs.end());
}
};
My questions:
- Is it better to use pointers in this case? I should always have a unique Object for B! In other words if content of two b objects are different they are still different because different address in memory.
- I want to write this code with help of smart_pointers in C++ 11! Which type is better
shared_ptr
orunique_ptr
? A B object is never owned by two objects and it has always one owner so I guessunique_ptr
is better but I am not sure. - How Can I write the code above using unique_ptr?
I would only use
unique_ptr
if you have to. You may prefer to makeB
a move-only type (likeunique_ptr
) to restrict ownership.If
B
is expensive to move or it is not practical to prevent the copying ofB
then useunique_ptr
but be aware that you are then paying for a dynamic memory allocation.Here is how you could use a move-only
B
in an example inspired by your code. If you useunique_ptr
instead it should work exactly the same:Live demo.
If copy-constructing
B
is costly, then (smart)pointers are probably a good idea (redesigning the application logic might be another solution),If I understood correctly, a given
B
instance is always manipulated by a single owner (eitherA
orC
).std::unique_ptr
is therefore a reasonable choice,Try the following implementation. I haven't compiled it but I think you'll get the general idea :)
.