【发布时间】:2022-01-18 09:07:20
【问题描述】:
今天我看到了这段代码,我想知道在创建新对象的赋值中这个 const 引用到底是做什么的。 (我不知道如何命名这种作业。)
std::string const& p = s.c_str(); // s is a std::string
我知道像 std::string const& p = s; 这样的东西会创建一个引用 p 到 s,但在显示的行中,我们正在创建一个新对象(使用来自 std::string::c_str 的原始指针)。
我在Coliru 中创建了一个 MCVE:
#include <iostream>
#include <string>
void foo(std::string const& s)
{
std::string const& p = s.c_str(); // << here
std::cout << s << " " << p << " " << &s << " " << &p << std::endl;
}
int main()
{
foo("hello");
}
而且,正如预期的那样,输出显示创建了一个新对象:
hello hello 0x7ffdd54ef9a0 0x7ffdd54ef950
所以,我的问题是:这真的是在做我看不到的事情吗?代码中是否有任何问题(如悬空引用)?
【问题讨论】:
-
我曾经偶然发现一个 Q/A,其中讨论了 const 引用中临时变量的生命周期。对我来说,令人惊讶的是,生命周期实际上是直到定义 const 引用的范围结束。Does a const reference class member prolong the life of a temporary?,Returning temporary object and binding to const reference,GotW #88: A Candidate For the “Most Important const”
-
非常感谢!这也说明了很多
标签: c++ c++14 variable-assignment const-reference