这是我发现的实现“三法则”的示例:
class Array {
public:
int size;
int* vals;
Array() : size(0), vals(NULL){}
Array( int s, int* v );
Array(const Array&); // 1
Array& operator=(const Array&); // 2
~Array(); // 3
};
Array::~Array() {
delete []vals;
vals = NULL;
}
Array::Array( int s, int* v ){
size = s;
vals = new int[size];
std::copy( v, v + size, vals );
}
Array::Array(const Array& rhs):
size(rhs.size),
vals((rhs.size) ? new int[size] : NULL)
{
if(size)
std::copy(rhs.vals, rhs.vals + rhs.size, vals);
}
Array& Array::operator=(const Array& rhs){
// if(this == &rhs) // no need
// return *this;
int* a = (rhs.size)? new int[rhs.size] : NULL; // this is why we don't need the above check: if this line throws then vals is untouched. if this is ok (local variable) then continue (next won't throw).
std::copy(rhs.vals, rhs.vals + rhs.size, a); // copying to a even (self assignment won't harm)
delete[] vals;
vals = a;
size = rhs.size;
return *this;
}
正如您在上面看到的,复制赋值运算符中的检查被删除,因为创建局部变量然后删除成员指针并将其分配给局部变量。但是,如果我写,我最重要的是:
int main() {
int vals[ 4 ] = { 11, 22, 33, 44 };
Array a1( 4, vals );
a1 = a1; // here I assigned a1 to itself
return 0;
}
我分配a1
给自己这是否意味着a1
'vals
被删除,然后a
在复制分配运算符中分配了本地?这是正确的方法吗?我的代码有一些陷阱吗?
- 任何提示,建议都非常感谢。