use*_*747 3 c++ language-lawyer temporary-objects c++11 dangling-pointer
N3290 C++草案,第12.2节,第5点,第10行.
第二个上下文是引用绑定到临时的.绑定引用的临时对象或绑定引用的子对象的完整对象的临时对象在引用的生命周期内持续存在,除了:
在new-initializer(5.3.4)中对引用的临时绑定将持续到包含new-initializer的full-expression完成为止.[例如:
Run Code Online (Sandbox Code Playgroud)struct S { int mi; const std::pair<int,int>& mp; }; S a { 1, {2,3} }; S* p = new S{ 1, {2,3} };// Creates dangling reference- 结束示例] [注意:这可能会引入悬空引用,并鼓励实现在这种情况下发出警告. - 结束说明]
与C++ 03相比,这是一个补充点.但这个例子对我来说是不可理解的.你能用其他任何例子来解释这一点吗?
我知道悬空引用和临时对象是什么,并且std::pair包含两个可能不同数据类型的值.
Temporaies一般只持续到它们创建的表达式的结尾:
#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 ';'
Run Code Online (Sandbox Code Playgroud)
如果创建临时对象并将其绑定到引用.您将其寿命延长到与其绑定的参考相同的寿命.
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)
Run Code Online (Sandbox Code Playgroud)
此规则的例外情况是临时绑定到新初始值设定项中的引用.
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 ';'
Run Code Online (Sandbox Code Playgroud)
但是在这里我们将新的临时对象绑定到成员
const std::pair<int,int>& mp;
这是一个const引用.但它所绑定的临时对象将在';'处被销毁.在上面的表达式中,当你尝试在后续表达式中使用它时,mp将引用一个不再存在的对象.
}
Run Code Online (Sandbox Code Playgroud)