临时性通常只持续到创建它们的表达式的结尾:
#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;
这是一个常量引用。但是它所绑定的临时对象将在';'处被销毁 在上面的表达式中,当您尝试在后续表达式中使用它时,mp 将是对不再存在的对象的引用。
}