K.Robert K.Robert - 1 month ago 15
C++ Question

Is this copy assignment operation safe?


class HasPtr {
HasPtr(const std::string &s = std::string()) :
ps(new std::string(s)), i(0) {}
HasPtr(const HasPtr &orig) :ps(new std::string(*orig.ps)), i(orig.i) {}
HasPtr &operator=(const HasPtr &rhs) {
*ps = *rhs.ps;
i = rhs.i;
return *this;
std::string *ps;
int i;

When I assign a HasPtr whose data member ps points to a large string to another,
is there any the possibility that I cause a memory corruption? for example:

HasPtr a;
HasPtr b(string("123456789...123456789"));


Hold the std::string by value. Besides being a string abstraction, it's also a resource management class, so use it as such. If you do, your class will be rule of 0/3/5 compliant without any extra effort from you.