2016-08-16: copy-and-swap

#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 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/zhouLee/p/5775483.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值