rvalue hello world缺少构造函数

时间:2013-01-12 20:27:19

标签: c++ c++11 clang

我试图了解更多有关右值参考的信息,但我仍然坚持这个最简单的例子:

#include <iostream>
using namespace std;

struct C {
    C() { cout << "C()\n"; }
    ~C() { cout << "~C()\n"; }
    C(const C&) { cout << "C(const C&)\n"; }
    C& operator=(const C&) { cout << "operator=(const C&)\n"; return *this; }

    C(C&&) { cout << "C(C&&)\n"; }
    C& operator=(C&&) { cout << "operator=(C&&)\n"; return *this; }
};

C foo() { C c; return c; }

int main()
{
    const C c = foo();
    return 0;
}

我用Clang 3.2和-std=c++11 -fno-elide-constructors编译了它(以避免(N)RVO),但结果让我感到惊讶:

C()
~C()    // huh?
C(C&&)
~C()
~C()

除了第一个~C()之外我完全相信。它来自哪里,我失踪了什么因为有2个结构和3个破坏?是和&amp;&amp;用被破坏的对象引用调用的构造函数??

1 个答案:

答案 0 :(得分:3)

这一定是个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