【问题标题】:C++ dangling const reference to a temporary objectC++ 悬空 const 对临时对象的引用
【发布时间】:2013-09-05 11:17:23
【问题描述】:

为什么下面的代码中有一个悬空引用?我认为对 const 的引用总是会将临时对象的寿命延长到它们的范围内。

boost::filesystem::recursive_directory_iterator it(dir_name);
const std::string& extension = it->path().extension().string();
std::cout << extension << std::endl; // error, dangling reference

【问题讨论】:

  • "[...]对 const 的引用总是将临时对象的生命周期延长到它们的范围内"。他们为什么要这样做?
  • 什么告诉你它是一个悬空引用??
  • @JBL:因为语言标准是这样说的。只要初始化器实际上是一个临时的。
  • @MikeSeymour 哦,谢谢!你能指出部分吗? (我找不到它与哪个相关)。

标签: c++ reference boost-filesystem


【解决方案1】:

documentationclass path

描述为返回const string的成员函数被允许返回const string&amp;

所以不能保证string() 实际上会返回一个临时字符串。它可能是对extension()返回的临时path内的字符串的引用;这将延长其生命周期,因为它直接绑定到本地引用。

【讨论】:

    【解决方案2】:

    不要将extension 设为常量引用。改为这样做:

    const std::string extension = it->path().extension().string();
    

    【讨论】:

    • 我认为提问者理解这种可能性,但想知道为什么他们的代码不像most important const
    猜你喜欢
    • 2017-07-09
    • 2010-10-20
    • 1970-01-01
    • 1970-01-01
    • 2015-05-23
    • 1970-01-01
    • 1970-01-01
    • 2019-07-02
    • 1970-01-01
    相关资源
    最近更新 更多