Stay Hungry , Stay Foolish

君子生非异也,善假于物也

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
#include <algorithm> // std::copy
#include <cstddef> // std::size_t
#include <stdio.h>

class dumb_array
{
public:
    // (default) constructor
    dumb_array(std::size_t size = 0)
        : mSize(size),
          mArray(mSize ? new int[mSize]() : 0)
    {
        printf("construct %p\n", this);
    }

    // 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
        printf("copy-constructor %p\n", this);
        std::copy(other.mArray, other.mArray + mSize, 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)
    {
        printf("other %p, operator= %p\n", &other, this);
        swap(*this, other); // (2)
        return *this;
    }

    // destructor
    ~dumb_array()
    {
        printf("destruct %p\n", this);
        delete [] mArray;
    }

private:
    std::size_t mSize;
    int* mArray;
};

int main()
{
    dumb_array obj(100);
    printf("test copy-constructor\n");
    dumb_array copy_obj(obj);
    
    printf("test operator=\n");
    dumb_array operator_obj;
    operator_obj = obj;
    
    return 0;
}

/*
construct 0x7fffdd3b4730
test copy-constructor
copy-constructor 0x7fffdd3b4720
test operator=
construct 0x7fffdd3b4710
copy-constructor 0x7fffdd3b4740
other 0x7fffdd3b4740, operator= 0x7fffdd3b4710
destruct 0x7fffdd3b4740
destruct 0x7fffdd3b4710
destruct 0x7fffdd3b4720
destruct 0x7fffdd3b4730
*/

参考资料

What is the copy-and-swap idiom?

More C++ Idioms/Copy-and-swap

posted on 2016-08-16 10:41  octocat  阅读(312)  评论(0编辑  收藏  举报