为什么C ++ 11的移动构造函数/赋值操作符不如预期 [英] Why do not C++11's move constructor/assignment operator act as expected
本文介绍了为什么C ++ 11的移动构造函数/赋值操作符不如预期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#include <iostream>
using namespace std;
struct A
{
A()
{
cout << "A()" << endl;
}
~A()
{
cout << "~A()" << endl;
}
A(A&&)
{
cout << "A(A&&)" << endl;
}
A& operator =(A&&)
{
cout << "A& operator =(A&&)" << endl;
return *this;
}
};
struct B
{
// According to the C++11, the move ctor/assignment operator
// should be implicitly declared and defined. The move ctor
// /assignment operator should implicitly call class A's move
// ctor/assignment operator to move member a.
A a;
};
B f()
{
B b;
// The compiler knows b is a temporary object, so implicitly
// defined move ctor/assignment operator of class B should be
// called here. Which will cause A's move ctor is called.
return b;
}
int main()
{
f();
return 0;
}
我的预期输出应为:
A()
A(A&&)
~A()
~A()
However, the actual output is: (The C++ compiler is: Visual Studio 2012)
A()
~A()
~A()
这是VC ++的错误吗?
Is this a bug of VC++? or just my misunderstanding?
推荐答案
根据这篇博文,VC ++ 2012目前实现了 N2844 + DR1138 ,但不能 N3053 。因此,编译器不会为您隐式生成移动构造函数或赋值运算符。如果你添加显式默认和移动构造函数到 B
,那么你会得到你期望的输出。
According to this blog post, VC++ 2012 currently implements N2844 + DR1138, but not N3053. As a result, the compiler is not implicitly generating move constructors or assignment operators for you. If you add explicit default and move constructors to B
then you will get the output you expect.
这篇关于为什么C ++ 11的移动构造函数/赋值操作符不如预期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文