Consider the following class:
class A {
char *p;
int a, b, c, d;
public:
A(const &A);
};
Note that I have to define a copy constructor
Replace char*
with std::string
.
Unless your class has one function, which is managing a resource, you should never manage any resources directly. Always use a smart pointer or custom management class of some description. Typically, it's best to leave the implicit copy constructor, if you can. This approach also allows easy maintenance of the destructor and assignment operators.
You really should use smart pointers here.
This would avoid rewriting both the copy constructor and the affectation operator (operator=
).
Both of these are error prone.
A common mistake with the operator=
is implementing it that way:
SomeClass& operator=(const SomeClass& b)
{
delete this->pointer;
this->pointer = new char(*b.pointer); // What if &b == this or if new throws ?
return *this;
}
Which fails when one does:
SomeClass a;
a = a; // This will crash :)
Smart pointers already handle those cases and are obviously less error prone.
Moreover, Smart pointers, like boost::shared_ptr
can even handle a custom deallocation function (by default it uses delete
). In practice, I rarely faced a situation where using a smart pointer instead of a raw pointer was unpractical.
Just a quick note: boost
smart pointer class, are header-only designed (based on templates) so they don't require additional dependencies. (Sometimes, it matters) You can just include them and everything should be fine.