一般に、テンポラリは、それらが作成された式の最後までしか持続しません:
#include <complex>
void func()
{
std::complex<int> a; // Real variable last until the end of scope.
a = std::complex<int>(1,2) + std::complex<int>(3,4);
// ^^^^^^^^^^^^^^^^^^^^^^ Creates a temporary object
// This is destroyed at the end of the expression.
// Also note the result of the addition creates a new temporary object
// Then uses the assignment operator to change the variable 'a'
// Both the above temporaries and the temporary returned by '+'
// are destroyed at ';'
一時オブジェクトを作成して参照にバインドする場合。その寿命を、それがバインドされている参照と同じ寿命まで延長します。
std::complex<int> const& b = std::complex<int>(5,6);
// ^^^^^^^^^^^^^^^^ Temporary object
// ^^^^ Bound to a reference.
// Will live as long as b lives
// (until end of scope)
このルールの例外は、テンポラリが新しいイニシャライザの参照にバインドされている場合です。
S* p1 = new S{ 1, {2,3} };
// This is the new C++11 syntax that does the `equivalent off`:
S* p2 = new S {1, std::pair<int,int>(2,3) };
// ^^^^^^^^^^^^^^^^^^^^^^^ Temporary object.
// This lives until the end of the
// expression that belongs to the new.
// ie the temporary will be destroyed
// when we get to the ';'
しかし、ここでは新しい一時オブジェクトをメンバーにバインドしています
const std::pair<int,int>& mp;
これは const 参照です。ただし、バインドされている一時オブジェクトは「;」で破棄されます したがって、mp は、後続の式で使用しようとすると存在しなくなったオブジェクトへの参照になります。
}