0

次の質問を読んでいました。

コピーアンドスワップの慣用句とは何ですか?

オブジェクトが値渡しされると、そのポインターと値がコピーされますが、渡されたオブジェクトのポインターが指すメモリはコピーされないという印象を受けました。したがって、リンク先の例のように代入演算子をオーバーロードすると、次のようになります。

#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);は新しいメモリを割り当て、前の配列の内容をコピーしますか?

4

1 に答える 1

1

コピーコンストラクターが実装したように、

dumb_array(const dumb_array& other) 
        : mSize(other.mSize),
          mArray(mSize ? new int[mSize] : 0),

mArray中身dumb_arrayが濃く写し出されました。ポインタをコピーしただけでなく、真新しい配列を作成し、コンテンツのコピーをstd::copy().

したがって、 whenoperator=(dumb_array other)が実行されるときthis->mArrayother.mArray(パラメーターは参照ではなくオブジェクトであるため、これはコピーです) は 2 つの異なる配列です。の後にswap()other.mArrayによって最初に保持されていたポインタが保持されthis->mArrayます。そしてoperator=()戻ってきたら、other.mArrayで削除できます~dumb_array()

于 2015-02-25T02:28:59.500 に答える