Reputation: 254
I'm trying to know more about rvalue references but I got stuck on this simplest example:
#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;
}
I've compiled it with Clang 3.2 and -std=c++11 -fno-elide-constructors
(to avoid (N)RVO) but the result is surprising to me:
C()
~C() // huh?
C(C&&)
~C()
~C()
I expected exactly that except for the first ~C()
. Where did it came from and what am I missing because there are 2 constructions and 3 destructions? Is the && constructor called with a destroyed object reference??
Upvotes: 9
Views: 169
Reputation: 126522
This must be a bug. The destructor for the local object constructed in foo()
is being invoked before the move constructor of the receiving object. In particular, it seems a temporary is allocated but not (move-)constructed when returning by value. The following program shows this:
#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;
}
Output:
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
Creating two objects inside of foo()
seems to shed some more light on the issue:
C foo() { C c(10); C d(14); return c; }
Output:
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
Interestingly, this seems to depend on how the object is constructed in foo()
. If foo()
is written this way:
C foo() { C c(10); return c; }
Then the error appears. If it is written this way it does not:
C foo() { return C(10); }
Output with this last definition of 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
Upvotes: 3