如下面的代码所示,复制赋值操作符必须检查输入对象指向自身还是其他位置。我想知道为什么复制构造函数不需要进行相同的检查。
我是C++新手,希望能得到这个问题的帮助。
我是C++新手,希望能得到这个问题的帮助。
class rule_of_three
{
char* cstring; // raw pointer used as a handle to a dynamically-allocated memory block
void init(const char* s)
{
std::size_t n = std::strlen(s) + 1;
cstring = new char[n];
std::memcpy(cstring, s, n); // populate
}
public:
rule_of_three(const char* s = "") { init(s); }
~rule_of_three()
{
delete[] cstring; // deallocate
}
rule_of_three(const rule_of_three& other) // copy constructor
{
init(other.cstring);
}
rule_of_three& operator=(const rule_of_three& other) // copy assignment
{
if(this != &other) {
delete[] cstring; // deallocate
init(other.cstring);
}
return *this;
}
};
MyClass foo(foo);
. - HolyBlackCatcstring
类中处理所有指针管理。如果你用unique_ptr
(或者根据你的需求使用shared_ptr
),很多内存管理的“工作”都可以省去。因为 unique ptr 可以重新分配(删除旧实例)并在销毁时也会整理好。 - code_fodder