Reputation: 22946
How do temporary objects get created during reference initialization by the compiler, and what does that mean?
From the C++ standard:
12.2 Temporary objects [class.temporary] Temporaries of class type are created in various contexts: binding a reference to a prvalue (8.5.3), returning 1 a prvalue (6.6.3), a conversion that creates a prvalue (4.1, 5.2.9, 5.2.11, 5.4), throwing an exception (15.1), entering a handler (15.3), and in some initializations (8.5).
From this link: http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8l.doc%2Flanguage%2Fref%2Fcplr382.htm
When a temporary object is created to initialize a reference variable, the name of the temporary object has the same scope as that of the reference variable.
Upvotes: 2
Views: 320
Reputation: 17587
From your edit: 12.2 states that a temporary is created in the cases when you initialize a const reference where it refers to a prvalue. For example:
double d = 3.14;
const int &r = d;
the compiler transforms this code into something like this:
int temp = d; // creates a temporary int
const int &r = temp; // reference is bound to that temporary
The lifetime of temporary that is bound to a const reference is the lifetime of the reference. i.e. the temporary is destroyed when the reference goes out of the scope.
Upvotes: 2