在C++ 11中,我们可以编写以下代码:
struct Cat {
Cat(){}
};
const Cat cat;
std::move(cat); //this is valid in C++11
Run Code Online (Sandbox Code Playgroud)
当我打电话时std::move,这意味着我想移动对象,即我将改变对象.移动const对象是不合理的,为什么不std::move限制这种行为呢?这将是未来的陷阱,对吧?
陷阱意味着布兰登在评论中提到:
"我认为他的意思是"偷偷摸摸"他鬼鬼祟祟偷偷摸摸,因为如果他没有意识到,他最终得到的副本并不是他想要的."
在Scott Meyers的"Effective Modern C++"一书中,他给出了一个例子:
class Annotation {
public:
explicit Annotation(const std::string text)
: value(std::move(text)) //here we want to call string(string&&),
//but because text is const,
//the return type of std::move(text) is const std::string&&
//so we actually called string(const string&)
//it is a bug which is very hard to find out
private:
std::string value;
};
Run Code Online (Sandbox Code Playgroud)
如果 …
我正在阅读有关std::move移动构造函数和移动赋值运算符的内容.说实话,我现在得到的只是困惑.现在我有一节课:
class A{
public:
int key;
int value;
A(){key = 3; value = 4;}
//Simple move constructor
A(A&& B){ A.key = std::move(B.key);
A.value = std::move(B.value);}
};
Run Code Online (Sandbox Code Playgroud)
B是一个右值参考,为什么你可以申请std::moveravlue参考的成员?B.key和B.value已被移动,都已经失效,但如何B作为类的一个对象A被失效?A a(A()),A()显然是一个rvlaue,可以A()被移动std::move,为什么?同样,如果我有一个功能
int add(int && z){
int x = std:move(z);
int y = std:move(z);
return x+y;
}
如果我打电话add(5),怎么可以5移动,为什么?并且注意到z已经移动了两次,在z第一次移动之后,它已经失效,你怎么能再次移动它?
foo (T …