【发布时间】:2023-03-21 21:24:01
【问题描述】:
将临时对象绑定到 const 引用会延长其生命周期;参看。 GotW #88.
为什么这在这个 sn-p 上不起作用?直播here。
#include <iostream>
#include <string>
struct A {
A() : s("abc") {}
const std::string& s;
};
struct B {
const std::string& s = "def";
};
int main() {
A a;
std::cout << a.s << std::endl;
B b;
std::cout << b.s << std::endl;
}
额外问题:如何使用 gcc 触发警告?
【问题讨论】:
-
引用您链接的 GotW:“请注意,这仅适用于基于堆栈的引用。它不适用于作为对象成员的引用”。
-
是的,这就是 R Sahu 在他的回答中提到的。谢谢。
标签: c++ reference lifetime string-literals