问题描述
考虑下面的类:
class A
{
public:
std :: string field_a;
std :: string field_b;
}
现在考虑以下副本构造:
A a1(a2);
复制结构将充分复制 A
缺少一个显式的拷贝构造函数,因为 std :: string
的拷贝构造函数将被编译器生成的隐式拷贝构造函数调用。
$
编辑:测试显示:
A a2(std :: move(a1));
实际上会导致复制构造,除非特定的move构造函数:
A(A&& other):a(std :: move(other.a)){}
已定义。
EDIT EDIT
我ping了Stephan T Lavavej,问他为什么VC 2012似乎不遵循12.8中关于隐式移动构造函数生成的草案。他很善良地解释:
解决方案是的,从C ++ 11草案,12.8:
后面的条件指定更多细节:
很明显,移动构造函数将被隐式声明为:
- 该类没有用户声明的任何其他特殊成员函数。
- 移动构造函数可以通过移动其所有成员和基数来实现。
您的类显然符合这些条件。
Consider the following class:
class A { public: std::string field_a; std::string field_b; }
Now consider the following copy construction:
A a1(a2);
The copy construction will adequately copy
A
despite the lack of of an explicit copy constructor because the copy constructors forstd::string
will be called by the compiler generated implicit copy constructor.What I wish to know is, is the same true for move construction?
EDIT: Testing here shows that:
A a2(std::move(a1));
Will actually result in a copy construction, unless the specific move constructor:
A( A && other ) : a(std::move(other.a)) {}
Is defined.
EDIT EDITI pinged Stephan T Lavavej and asked him why VC 2012 doesn't seem to follow what draft 12.8 states regarding implicit move constructor generation. He was kind enough to explain:
解决方案Yes, from the C++11 draft, 12.8:
The latter condition is specified with more detail later:
Plainly speaking, the move constructor will be implicitly declared if:
- The class does not have user-declared any of the other special member functions.
- The move constructor can be sensibly implemented by moving all its members and bases.
Your class obviously complies with these conditions.
这篇关于移动构造函数是隐式的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!