Jas*_*onS 4 c++ move-semantics c++11
有人可以帮助我理解std::move吗?
我认为如果r值引用超出范围,那么如果使用std::move运算符分配它也会引用它.为什么以下代码不是这种情况?
#include<iostream>
using namespace std;
int main()
{
string one = "1 - one";
string two = "2 - two";
{
//not as expected
string & lValRef = one;
string && rValRef = std::move(two);
string newS(rValRef);
}
cout << "one : " << one << endl;
cout << "two : " << two << endl;
{
//as expected
string temp(std::move(one));
string tempAssignment;
tempAssignment = std::move(two);
}
cout << "one : " << one << endl;
cout << "two : " << two << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
你可以在这里摆弄它.
我一直认为使用std::move是一种将对象保持在"可删除状态"的方法.所以我很惊讶'两个'第一次打印出任何东西.有没有像我一样创建&& r-value引用('rValRef')?[我明白std::move()在我的'rValRef'周围需要一个,因为它可以按照需要工作].
下面是我自己的代码,我曾经帮助我更好地理解这一点.如果你愿意,请玩它:)代码在这里.
#include <iostream>
#include <vector>
using namespace std;
class SimpleClass {
friend ostream& operator<<(ostream & s,const SimpleClass & rhs);
private:
vector<char> data;
public:
SimpleClass(initializer_list<char> lst):data(lst.size()) {
copy(lst.begin(),lst.end(),data.begin());
}
SimpleClass(size_t dim = 0):data(dim){};
virtual ~SimpleClass() = default;
SimpleClass(const SimpleClass & rhs) = default;
SimpleClass & operator=(const SimpleClass & rhs) = default;
SimpleClass(SimpleClass && rhs):data(move(rhs.data)){};
SimpleClass & operator=(SimpleClass && rhs){
if (this != &rhs){
this->data = move(rhs.data);
return *this;
}
}
};
ostream& operator<<(ostream & s,const SimpleClass & rhs){
for (size_t i = 0; i != rhs.data.size(); ++i)
s << rhs.data[i];
return s;
}
int main()
{
SimpleClass one = {'o','n','e'};
SimpleClass two = {'t','w','o'};
{
SimpleClass & lValRef = one;
SimpleClass && rValRef = std::move(two);
}
cout << "one : " << one << endl;
cout << "two : " << two << endl;
{
SimpleClass temp(std::move(one));
SimpleClass tempAssignment;
tempAssignment = std::move(two);
}
cout << "one : " << one << endl;
cout << "two : " << two << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这里要理解的是,引用类型是与值类别不同的概念.
string && rValRef = std::move(two);
string newS(rValRef);
Run Code Online (Sandbox Code Playgroud)
在第二行,类型rValRef是右值引用std::string,但值类别rValRef是左值.一个很好的经验法则是,如果你可以取一些东西的地址,它可能是一个左值.rValRef是一个命名变量,你可以获取地址,左边是左值.
如果要实际从引用移动,则需要std::move再次调用,以便表达式具有正确的值类别(具体而言,std::move返回xvalue,这是一种rvalue):
string newS(std::move(rValRef));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
124 次 |
| 最近记录: |