- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
考虑以下类:
class A
{
public:
std::string field_a;
std::string field_b;
}
现在考虑以下复制结构:
A a1(a2);
尽管没有显式的复制构造函数,复制构造仍将充分复制 A
,因为 std::string
的复制构造函数将由编译器生成的隐式调用复制构造函数。
我想知道的是, move 构造是否也是如此?
编辑:测试here表明:
A a2(std::move(a1));
实际上会导致复制构造,除非特定的 move 构造函数:
A( A && other ) : a(std::move(other.a)) {}
已定义。
编辑编辑我联系了 Stephan T Lavavej,问他为什么 VC 2012 似乎没有遵循 12.8 草案中关于隐式 move 构造函数生成的规定。他好心解释:
It's more of a "feature not yet implemented" than a bug. VC currently implements what I refer to as rvalue references v2.0, where move ctors/assigns are never implicitly generated and never affect the implicit generation of copy ctors/assigns. C++11 specifies rvalue references v3.0, which are the rules you're looking at.
最佳答案
是的,来自 C++11 草案,12.8:
If the definition of a class X does not explicitly declare a move constructor, one will be implicitly declaredas defaulted if and only if
- X does not have a user-declared copy constructor,
- X does not have a user-declared copy assignment operator,
- X does not have a user-declared move assignment operator,
- X does not have a user-declared destructor, and
- the move constructor would not be implicitly defined as deleted.
后面会详细说明最后一个条件:
An implicitly-declared copy/move constructor is an inline public member of its class. A defaulted copy/move constructor for a class X is defined as deleted (8.4.3) if X has:
- a variant member with a non-trivial corresponding constructor and X is a union-like class,
- a non-static data member of class type M (or array thereof) that cannot be copied/moved becauseoverload resolution (13.3), as applied to M’s corresponding constructor, results in an ambiguity or afunction that is deleted or inaccessible from the defaulted constructor,
- a direct or virtual base class B that cannot be copied/moved because overload resolution (13.3), asapplied to B’s corresponding constructor, results in an ambiguity or a function that is deleted orinaccessible from the defaulted constructor,
- any direct or virtual base class or non-static data member of a type with a destructor that is deletedor inaccessible from the defaulted constructor,
- for the copy constructor, a non-static data member of rvalue reference type, or
- for the move constructor, a non-static data member or direct or virtual base class with a type that does not have a move constructor and is not trivially copyable.
简单地说, move 构造函数将在以下情况下被隐式声明:
你的类(class)显然符合这些条件。
关于c++ - move 构造函数可以是隐式的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13344800/
我是一名优秀的程序员,十分优秀!