我正试图围绕 C++ 中的复制赋值运算符,我想知道如果对象为空,是否有办法创建一个新实例。
class Person {
public:
Person(string name) { pName_ = new string(name); }
~Person() { delete pName_; }
Person(const Person& rhs) {
if (pName_ != NULL) delete pName_;
pName_ = new string(*(rhs.pName()));
}
Person& operator=(const Person& rhs) {
cout << "begin copy..." << endl;
if (this == NULL) {
Person* p = new Person(rhs);
cout << "end copy null..." << endl;
return *p; // Not working?
}
delete pName_;
pName_ = new string(*(rhs.pName()));
cout << "end copy..." << endl;
return *this;
};
string* pName() const { return pName_; }
void printName() { cout << *pName_ << endl; }
private:
string* pName_;
};
int main() {
Person *a = new Person("Alex");
Person *b = new Person("Becky");
Person *c = NULL;
*b = *a; // copy works
*c = *a; // copy doesn't
if (a != NULL) a->printName(); // Alex
if (a != NULL) delete a;
if (b != NULL) b->printName(); // Alex
if (b != NULL) delete b;
if (c != NULL) c->printName(); // NULL
if (c != NULL) delete c;
return 0;
}
这是输出:
begin copy...
end copy...
begin copy...
end copy null...
Alex
Alex
有什么我可以在我的代码中更改以使其工作的东西,还是我什至不应该尝试尝试的东西?