Considering the following classes:
class A {
public:
A() {};
protected:
int m1;
float m2;
// ...
}
class B {
public:
B() { };
void add1(std::shared_ptr<A> _obj) {
data.push_back(_obj);
};
void add2(A* _obj) {
data.push_back(_obj);
};
void add3(A& _obj) {
data.push_back(&_obj);
};
private:
std::vector<std::shared_ptr<A>> data;
}
which of the methods addX in class B would be more suited/best practice for passing a new pointer into the vector? Considering that data is a vector of non-const smart pointers, I understand it is not possible to pass the object or the smart pointer by const reference without having to "de-const" them which is not advisable and considered bad practice. However, unless I am mistaken, all those methods end up instantiating a shared_ptr and then copying it into the vector? What are the differences between them?
add?B? Both? - Yksisarvinenshared_ptr. Instances ofAare however, are assumed to be instantiated outside the scope ofB, but after appended to the member vector, B can do whatever with it. - joaocandreB, becauseBwilldeletethe pointer. And you need to make that very clear in documentation. - Yksisarvinenstd::unique_ptr<A>or astd::weak_ptr<A>.add1would accept either - Calethshared_ptr? Isunique_ptrfor instance smaller and thus simpler to move? - joaocandre