#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;
}
我的預期產出應不C++ 11的移動構造函數/賦值運算符的行爲:爲什麼預期
A()
A(A&&)
~A()
~A()
然而,實際的輸出是:(C++編譯器是:的Visual Studio 2012 )
A()
~A()
~A()
這是VC++的bug嗎?或者只是我的誤解?
爲什麼你期望'A'的移動賦值操作符被調用? – Praetorian
@Prætorian:當RVO未被應用時,C++ 11說'return b'應該將'b'移到返回值中。也許Visual Studio 2012只是不正確地實現C++ 11? –
@KevinBallard是的,'b'應該移動。但是,這會導致調用'A'的move *構造函數*,而不是移動*賦值運算符*。 – Praetorian