【发布时间】:2012-09-20 18:38:57
【问题描述】:
#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()
但是,实际的输出是:(C++编译器是:Visual Studio 2012)
A()
~A()
~A()
这是 VC++ 的错误吗?还是只是我的误会?
【问题讨论】:
-
你为什么期望
A的移动赋值运算符被调用? -
@Prætorian:当不应用 RVO 时,C++11 说
return b应该将b移动到返回值中。也许 Visual Studio 2012 只是没有正确实现 C++11? -
@KevinBallard 是的,
b应该被移动。但这应该导致调用A的移动构造函数,而不是移动赋值运算符。 -
@Prætorian:啊,你说得很好。
-
当心 C++11 是最近的标准。并不是所有的编译器都能马上搞定一切。
标签: c++ visual-c++ c++11 visual-studio-2012 move-semantics