我正在阅读以下问题:
我的印象是,当一个对象按值传递时,它的指针和值被复制,但传递的对象指针指向的内存没有被复制。因此,当从链接到示例中重载赋值运算符时:
#include <algorithm> // std::copy
#include <cstddef> // std::size_t
class dumb_array
{
public:
// (default) constructor
dumb_array(std::size_t size = 0)
: mSize(size),
mArray(mSize ? new int[mSize]() : 0)
{
}
// copy-constructor
dumb_array(const dumb_array& other)
: mSize(other.mSize),
mArray(mSize ? new int[mSize] : 0),
{
// note that this is non-throwing, because of the data
// types being used; more attention to detail with regards
// to exceptions must be given in a more general case, however
std::copy(other.mArray, other.mArray + mSize, mArray);
}
// destructor
~dumb_array()
{
delete [] mArray;
}
friend void swap(dumb_array& first, dumb_array& second) // nothrow
{
// enable ADL (not necessary in our case, but good practice)
using std::swap;
// by swapping the members of two classes,
// the two classes are effectively swapped
swap(first.mSize, second.mSize);
swap(first.mArray, second.mArray);
}
dumb_array& operator=(dumb_array other) // (1)
{
swap(*this, other); // (2)
return *this;
}
private:
std::size_t mSize;
int* mArray;
};
...复制对象的析构函数如何不消除指向的资源,mArray
?现在正在完成分配的对象是否没有一个mArray
指向可能已释放内存的复制指针?该行是否swap(first.mArray, second.mArray);
分配新内存并复制前一个数组的内容?