I’m trying to understand copy assignment in C++. I know it’s best to use copy-and-swap idiom for this operator. But for this simple class without consider the Exception safety, when will *ps = *(h.ps);
fail? could you please provide some examples where this can go wrong? thanks
class HasPtr {
public:
HasPtr(std::string const & s = std::string()):
ps(new std::string(s)), i(0) {}
HasPtr(HasPtr const & h):
ps(new std::string(*(h.ps))), i(h.i) {}
HasPtr & operator = (HasPtr const & h) {
*ps = *(h.ps);
i = h.i;
return *this;
}
~HasPtr(){ delete ps;}
private:
std::string * ps;
int i;
};
I’ve tried to use GPT, it says there will be a memory leak, but I just can’t see it
New contributor
paul m is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
5