例如,我的一本书中的这样的代码:
class HasPtr {
public:
HasPtr(const HasPtr& h): ps(new std::string(*h.ps)), i(h.i) { }
HasPtr(const std::string &s = std::string()): ps(new std::string(s)), i(0) { }
HasPtr& operator=(const HasPtr&);
~HasPtr() { delete ps; }
private:
std::string *ps;
int i;
};
HasPtr& HasPtr::operator=(const HasPtr &rhs){
auto newp = new string(*rhs.ps); // copy the underlying string
delete ps; // free the old memory
ps = newp; // copy data from rhs into this object
i = rhs.i;
return *this; // return this object
}
似乎 operator= 的内部可能只是:
*ps = *rhs.ps
i = rhs.i
return *this;
无需先删除指针,这样做似乎是多余的。它确实提到它的编写方式是在发生异常时使对象处于合适的状态,但没有透露过去,但我看不出会发生什么异常,即使我的替代方案也无法处理。为什么在分配之前需要先删除对象?