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()};
}
在哪些上下文中,语言允许或实际首选移动构造函数?临时返回值似乎可以移动(和垃圾内容),但我想找到所有可以静默使用移动的地方的核心语言规则。谢谢!
每当参数绑定到rvalue
引用时,编译器都可以使用移动。 每当参数为prvalue
时,编译器都会使用它(见下文)。 参数也可以转换为rvalue
引用。
通常,右值是出现在作业右侧的任何内容。 考虑它的一个粗略方法是是否可以在代码中引用它。 左值有身份,右值通常没有。
真的,有几种类型的左值和右值...
-
lvalue
- 有身份,不能移动 (lvalue
) -
xvalue
- 具有身份,可以移动(lvalue
和rvalue
) -
prvalue
- 没有身份,可以移动 (rvalue
)
xvalue
既是lvalue
,也是rvalue
。 例如,您使用 std::move
显式强制转换为rvalue
引用的内容。
此外,还有一个很好的介绍来重新定义引用和移动语义 http://www.cprogramming.com/c++11/rvalue-references-and-move-semantics-in-c++11.html
相关文章:
- 为什么不调用移动构造函数?(默认情况下只有构造器,没有别的)
- std::vector::p ush_back() 不会在 MSVC 上编译具有已删除移动构造函数的对象
- 仅包含可移动 std::map 的类的移动构造函数不起作用
- 为什么调用复制构造函数而不是移动构造函数?
- 基类中的默认析构函数禁用子类中的移动构造函数(如果有成员)
- 从具有按值捕获的 lambda 移动构造 std::函数时,移动构造函数调用两次
- 具有已删除移动和复制构造函数的类的就地构造
- 移动构造函数和右值引用
- 使用移动调用对等构造函数unique_ptr默认构造函数
- 为什么 std::memmove 中联合的默认非平凡移动构造函数C++?
- 具有专用化的模板类中的可靠条件复制和移动构造函数
- 构造函数采用std::string_view与std::string并移动
- C++:为什么不调用移动构造函数?
- 了解构造函数在移动、复制、赋值语义中的行为
- 没有移动的构造函数移动课程
- 引用绑定和复制构造函数/移动构造函数
- 构造函数移动
- C++ 向量实现 - 移动构造函数 - 移动与前进
- 我真的必须取消移动构造函数/移动结构中的所有成员还是只是指针
- 将类(没有默认构造函数)移动到另一个类的move构造函数中