小编Abd*_*man的帖子

编写移动副本和移动赋值构造函数的有效方法

以下赋值和副本移动构造函数是否最有效?如果有人有其他方式请告诉我?我的意思是什么回合std :: swap?并通过复制构造函数调用赋值在下面的代码中是安全的吗?

#include <iostream>
#include <functional>
#include <algorithm>
#include <utility>

using std::cout;
using std::cin;
using std::endl;
using std::bind;


class Widget
{

public:

    Widget(int length)
        :length_(length),
        data_(new int[length])
    {
        cout<<__FUNCTION__<<"("<<length<<")"<<endl;
    }

    ~Widget()
    {
        cout<<endl<<__FUNCTION__<<"()"<<endl;
        if (data_)
        {
            cout<<"deleting source"<<endl;
        } 
        else
        {
            cout<<"deleting Moved object"<<endl;
        }

        cout<<endl<<endl;
    }

    Widget(const Widget& other)
        :length_(other.length_),
        data_(new int[length_])
    {
        cout<<__FUNCTION__<<"(const Widget& other)"<<endl;
        std::copy(other.data_,other.data_ + length_,data_);
    }

    Widget(Widget&& other)
/*
        :length_(other.length_),
        data_(new int[length_])*/
    {
        cout<<__FUNCTION__<<"(Widget&& other)"<<endl;
        length_ = 0;
        data_ = nullptr;
        std::swap(length_,other.length_);
        std::swap(data_,other.data_);
    } …
Run Code Online (Sandbox Code Playgroud)

c++ constructor move variable-assignment c++11

4
推荐指数
1
解决办法
2976
查看次数

标签 统计

c++ ×1

c++11 ×1

constructor ×1

move ×1

variable-assignment ×1