Reputation: 30615
From my understanding the main reason to provide a user-defined copy constructor is because we need to ensure data member pointers are deep-copied.
Does this mean if we replace raw pointer data members with smart pointers, the frequency of providing user-defined copy constructors decreases?
Upvotes: 0
Views: 1389
Reputation: 21
The correct answer is no. You need to define a copy constructor for any class with pointer members (shared or otherwise) unless the value of the pointer is what needs to be copied. The exception implies that the memory contents at the address stored in the pointer are managed by another class.
The shared pointer maintains a reference count to manage the scope of the allocated memory, but it does not manage the memory contents or make copies of the referenced data. Thus the shared pointer frees the programmer from having to manage the scope of objects allocated on the heap. But it does not relieve the programmer of the need to define a copy constructor for objects that contain pointers to dynamically allocated data.
The term smart pointer is a synonym for shared pointer in this context. Specifically the smart pointer referred to is std::shared_ptr which keeps the reference count as described. The best way to avoid writing copy constructors is to follow the design pattern known as Resource Acquisition Is Initialization (RAII). This type of design pattern keeps member data allocated on the stack so that member destructors are called automatically when the stack unwinds.
The concept of designing smart pointers that do implicit copy operations really doesn't make sense. While it is possible to dereference the pointer to get at the data to be copied, the copy requires a new pointer. The whole idea of using pointers (or references) is to access a common memory region and avoid making copies.
Upvotes: 1
Reputation: 21773
Now the question has been modified, the answer is yes, if you use a smart pointer that performs a deep copy of the wrapped object, when this smart pointer is copied.
Previously regarding shared pointer only: No because copying a shared pointer, results in two shared pointers that point to the same object. If you have an object with a shared pointer to a subobject and copy it, and you want the new object to have its own copy of the subobject (deep copy), you will need to do that in a copy constructor or use a different kind of smart pointer.
Upvotes: 1
Reputation: 45664
Yes it does. If you only use types which know how to semantically copy your data, you have little need to overwrite the default copy constructor.
Upvotes: 1