![](/img/trans.png)
[英]Default constructors, initialization of POD and implicit type conversions in C++11
[英]C++11 implicit move constructors
我无法理解为什么以下内容(至少根据gcc 4.8)在C ++ 11中是合法的:
// This class manages a non-copyable resource.
struct B {
B();
B(B &&) { /* logging, etc., to verify if needed. */ }
private:
B(B const &);
B const &operator=(B const &);
};
B bar() {
B b;
// This is apparently allowed via the move constructor.
return b;
};
int main() {
// From this "side" of the call as well.
B b1 = bar();
B b2{bar()};
}
在哪种情况下,语言允许或实际上首选move构造函数? 临时返回值似乎可以移动(以及其中的垃圾内容),但是我想找到可以静默使用该移动的所有地方的核心语言规则。 谢谢!
只要参数绑定到rvalue
引用,编译器就可以使用移动。 每当参数为prvalue
时,编译器就会使用它(请参见下文)。 也可以将参数强制转换为rvalue
引用。
通常,右值是出现在分配右侧的任何内容。 考虑它的粗略方法是在代码中是否可以引用它。 左值具有身份,右值通常没有。
确实,有一些类型的左值和右值...
lvalue
-具有身份,无法移动( lvalue
) xvalue
具有标识,可以移动( lvalue
和rvalue
) prvalue
没有身份,可以移动( rvalue
) xvalue
既是lvalue
,又是rvalue
。 一个示例是您使用std::move
显式转换为rvalue
引用的内容。
此外,还有一个不错的介绍rvalue引用和移动语义的介绍http://www.cprogramming.com/c++11/rvalue-references-and-move-semantics-in-c++11.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.