在clang的C++ 11状态页面中遇到了一个名为"rvalue reference for*this"的提案.
我已经阅读了很多关于rvalue引用并理解它们的内容,但我认为我不知道这一点.我也无法使用这些条款在网上找到太多资源.
页面上的提案文件有一个链接:N2439(将移动语义扩展到*this),但我也没有从中获得太多的例子.
这个功能是什么?
以下赋值和副本移动构造函数是否最有效?如果有人有其他方式请告诉我?我的意思是什么回合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)