问题描述
请考虑:
std::string foo();
void bar() {
const std::string& r1 = foo();
static const std::string& r2 = foo();
}
我知道第一次调用 foo()
将扩展到 r1
的生命周期。
I know that the lifetime of the string resulting from the first call to foo()
will be extended to the lifetime of r1
.
虽然临时绑定到 r2
它会活到直到结束范围,还是仍然在那里,当 bar()
被重新输入?
What about the temporary bound to r2
, though? Will it live until the end of the scope or will it still be there when bar()
is re-entered?
注意:我不感兴趣的是特定的编译器是这样做的。 (我对我们使用的一个感兴趣,我可以轻松地测试。)我想知道什么标准对此说。
Note: I am not interested whether a particular compiler does so. (I am interested in the one we use, and I can test easily with that.) I want to know what the standard has to say on this.
推荐答案
临时扩展到参考的生命周期。
The temporary is extended to the lifetime of the reference.
- 在构造函数的 ctor-initializer (12.6.2)中临时绑定到引用成员,直到构造函数退出。
- 在函数调用(5.2.2)中临时绑定到引用参数,直到包含调用的 full-expression 完成。
- 的临时绑定到返回值的函数return语句(6.6.3)不会扩展;
-
暂时绑定到全部表达式 -initializer (5.3.4)一直持续到包含 new-initializer 的 full-expression 完成为止。 [示例:
- A temporary bound to a reference member in a constructor’s ctor-initializer (12.6.2) persists until the constructor exits.
- A temporary bound to a reference parameter in a function call (5.2.2) persists until the completion of the full-expression containing the call.
- The lifetime of a temporary bound to the returned value in a function return statement (6.6.3) is not extended; the temporary is destroyed at the end of the full-expression in the return statement.
A temporary bound to a reference in a new-initializer (5.3.4) persists until the completion of the full-expression containing the new-initializer. [ Example:
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
end example] [注意:这可能会引入一个悬挂引用,并且鼓励实现在这种情况下发出警告。 -end note]
—end example ] [ Note: This may introduce a dangling reference, and implementations are encouraged to issue a warning in such a case. —end note ]
因此,在这种情况下,它基本上直到程序结束。
So, in this case, it's essentially until the program ends.
我们当然可以测试这个很简单:
We can, of course, test this pretty trivially:
#include <iostream>
struct Tracked
{
Tracked() { std::cout << "ctor\n"; };
Tracked(const Tracked&) { std::cout << "copy\n"; };
~Tracked() { std::cout << "dtor\n"; };
};
void foo()
{
static const Tracked& ref = Tracked();
}
int main()
{
std::cout << "main()\n";
foo();
std::cout << "bye\n";
}
结果:
main()
ctor
bye
dtor
这篇关于rvalue的生命期绑定到静态const引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!