这一定是个bug。构造的本地对象的析构函数在foo()
接收对象的移动构造函数之前被调用。特别是,当按值返回时,似乎分配了一个临时但没有(移动)构造。以下程序显示了这一点:
#include <iostream>
using namespace std;
struct C
{
C(int z) { id = z; cout << "C():" << id << endl; }
~C() { cout << "~C():" << id << endl; }
C(const C& c) { id = c.id + 1; cout << "C(const C&):" << id << endl; }
C& operator=(const C&) { cout << "operator=(const C&)\n"; return *this; }
C(C&& c) { id = c.id + 1; cout << "C(C&&):" << id << endl;}
C& operator=(C&&) { cout << "operator=(C&&)\n"; return *this; }
int id;
};
C foo() { C c(10); return c; }
int main()
{
const C c = foo();
return 0;
}
输出:
C():10
// THE TEMPORARY OBJECT IS PROBABLY ALLOCATED BUT *NOT CONSTRUCTED* HERE...
~C():10 // DESTRUCTOR CALLED BEFORE ANY OTHER OBJECT IS CONSTRUCTED!
C(C&&):4198993
~C():4198992
~C():4198993
在内部创建两个对象foo()
似乎可以更清楚地说明这个问题:
C foo() { C c(10); C d(14); return c; }
输出:
C():10
C():14
~C():14
// HERE, THE CONSTRUCTOR OF THE TEMPORARY SHOULD BE INVOKED!
~C():10
C(C&&):1 // THE OBJECT IN main() IS CONSTRUCTED FROM A NON-CONSTRUCTED TEMPORARY
~C():0 // THE NON-CONSTRUCTED TEMPORARY IS BEING DESTROYED HERE
~C():1
有趣的是,这似乎取决于对象的构造方式foo()
。如果foo()
这样写:
C foo() { C c(10); return c; }
然后出现错误。如果它是这样写的,它不会:
C foo() { return C(10); }
最后一个定义的输出foo()
:
C():10 // CONSTRUCTION OF LOCAL OBJECT
C(C&&):11 // CONSTRUCTION OF TEMPORARY
~C():10 // DESTRUCTION OF LOCAL OBJECT
C(C&&):12 // CONSTRUCTION OF RECEIVING OBJECT
~C():11 // DESTRUCTION OF TEMPORARY
~C():12 // DESTRUCTION OF RECEIVING OBJECT