首先:看看三法则,在特定情况下是绝对必须的。也考虑一下五规则,虽然不是强制性的,但你会遗漏一个很好的优化机会......
析构函数现在delete[]
将是数组(这部分留给您......),然后复制构造函数将执行此操作:(深度)复制数据:
A::A(A const& other)
: a(other.a), b(new int[20]) // assuming you have a fixed size for those arrays;
// better: introduce a constant for to avoid magic
// numbers in code!
{
// you created a new array, but yet need to fill it with the others value
std::copy(other.b, other.b + 20, b);
}
好的,第一步。使用复制和交换习语,赋值运算符变得非常简单:
A& operator=(A other) // YES, no reference! This will invoke the copy (or move!)
// constructor of your class!
{
swap(*this, other); // you'll need to implement it yet!
return *this;
// at this point, the destructor of other will clean up data that was potentially
// contained in *this before...
}
最后是移动构造函数:
A::A(A&& other)
: a(0), b(nullptr)
{
swap(*this, other);
// again swapping??? well, sure, you want the data from other to be contained
// in *this, and we want to leave other in some kind of valid state, which the
// nullptr is fine for (it's fine to delete[] a null pointer, so you don't even
// need to check in the destructor...)
}
现在由你决定:class B
类似地......
旁注:使用智能指针std::unique_ptr
(std::unique_ptr
)。