Let's consider that I have defined some classes B and C.
Now, let's consider the following class:
class A{
public:
int att1;
int att2;
std::shared_ptr<B> b_ptr;
std::shared_ptr<C> c_ptr;
A(const A& a);
};
Now, the question is about how to implement the copy constructor.
Currently in the code, this is what is being done:
A::A(const A& a){
att1 = a.att1;
att2 = a.att2;
b_ptr = a.b_ptr;
c_ptr = a.c_ptr;
}
The last two lines will call the copy constructor of std::shared_ptr and increment the number of owners of the underlying pointer by 1.
But, isn't it a bad idea to have a copy constructor do that? It means that anywhere the copy constructor is called, it will actually have a relation with the initial object because the objects of class B and C aren't actually copied, but only the pointers are.
I realize that thanks to the use of shared_ptr, at least this will not be making any memory leaks.
Is it a common practice to do that? Is there any legitimate reason to do it? Or should I just avoid it all together?