K.Robert K.Robert - 7 days ago 8
C++ Question

Is this copy assignment operation safe?

#include<string>

class HasPtr {
public:
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;
}
private:
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"));
a=b;

Answer

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.

Comments