zoukankan      html  css  js  c++  java
  • 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
    ", 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
    ", 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
    ", &other, this);
            swap(*this, other); // (2)
            return *this;
        }
    
        // destructor
        ~dumb_array()
        {
            printf("destruct %p
    ", this);
            delete [] mArray;
        }
    
    private:
        std::size_t mSize;
        int* mArray;
    };
    
    int main()
    {
        dumb_array obj(100);
        printf("test copy-constructor
    ");
        dumb_array copy_obj(obj);
        
        printf("test operator=
    ");
        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

  • 相关阅读:
    (转)交换两个变量的值,不使用第三个变量的四种法方
    Java权威编码规范
    Git的安装和设置
    ActiveMQ简单入门
    JMS术语
    求助 WPF ListViewItem样式问题
    初步探讨WPF的ListView控件(涉及模板、查找子控件)
    圆角button
    用Inno Setup来解决.NetFramework安装问题
    [!!!!!]Inno Setup教程-常见问题解答
  • 原文地址:https://www.cnblogs.com/zhouLee/p/5775483.html
Copyright © 2011-2022 走看看