c++ - 这个 const 引用是否保留了它的生命?

标签 c++

我找到了 this answer问题"Does a const reference prolong the life of a temporary?" ,其中指出:

Only local const references prolong the lifespan.

恐怕我的标准语不达标,不知道下面的 foo 是否是本地常量引用。

我下面的 const std::string& foo 是否延长了在调用 get_or 时创建的临时 std::string 函数参数的生命周期>,或者我是否有悬空引用?

#include <iostream>
#include <boost/optional.hpp>

struct Foo
{
    const std::string& get_or(const std::string& def)
    {
        return str ? str.get() : def;
    }

    boost::optional<std::string> str;
};

int main()
{
    Foo f;
    const std::string& foo = f.get_or("hello world");

    std::cout << foo << '\n';
}

最佳答案

const& 在这种情况下不会延长生命周期。考虑 example here构造一个临时对象然后尝试打印它:它使用与您的代码相同的构造,但我对其进行了更改以使对象构造和销毁对用户更加明确。

#include <iostream>

struct reporting {
    reporting() { std::cout << "Constructed" << std::endl;}
    ~reporting() { std::cout << "Destructed" << std::endl;}
    reporting(reporting const&) { std::cout << "Copy-Constructed" << std::endl;}
    reporting(reporting &&) { std::cout << "Move-Constructed" << std::endl;}
    reporting & operator=(reporting const&) { std::cout << "Copy-Assigned" << std::endl; return *this;}
    reporting & operator=(reporting &&) { std::cout << "Move-Assigned" << std::endl; return *this;}

    void print() const {std::cout << "Printing." << std::endl;}
};

const reporting& get_or(const reporting& def)
{
    return def;
}

int main()
{
    const reporting& foo = get_or(reporting{});

    foo.print();
    return 0;
}

输出:

Constructed
Destructed
printing.

注意对象是如何在 printing. 显示之前销毁的。

您可能想知道为什么代码仍然完成且没有可见错误:这是未定义行为的结果。有问题的对象不存在,但是因为它不依赖于状态来调用它的方法,所以程序恰好没有崩溃。其他更复杂的示例不应该保证这会在不崩溃或导致其他意外行为的情况下工作。

顺便说一句,如果临时文件是 bound directly to the const&,情况会有些不同。 :

#include <iostream>

struct reporting {
    reporting() { std::cout << "Constructed" << std::endl;}
    ~reporting() { std::cout << "Destructed" << std::endl;}
    reporting(reporting const&) { std::cout << "Copy-Constructed" << std::endl;}
    reporting(reporting &&) { std::cout << "Move-Constructed" << std::endl;}
    reporting & operator=(reporting const&) { std::cout << "Copy-Assigned" << std::endl; return *this;}
    reporting & operator=(reporting &&) { std::cout << "Move-Assigned" << std::endl; return *this;}

    void print() const {std::cout << "printing." << std::endl;}
};

const reporting& get_or(const reporting& def)
{
    return def;
}

int main()
{
    const reporting& foo = reporting{};

    foo.print();
    return 0;
}

输出:

Constructed
printing.
Destructed

看看这个对象是如何在使用之后才被销毁的。在这种情况下,对象会一直存在到范围结束。

关于c++ - 这个 const 引用是否保留了它的生命?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44294210/

相关文章:

c++ - 循环时出现段错误

c++ - 如何将动态大小的纹理数组与 glTexImage2D 一起使用?

C++ | cout, 打印返回的对象

c++ - 是否可以使用 GTest 进行 ASSERT_DOES_NOT_COMPILE?

c++ - 为什么我不能直接将 __int64 变量设置为 -2500000000?

c++ - LRU缓存设计

c++ - 从 QLabel 获取 QPixmap

c++ - 使用数组参数的函数特化

c++ - 使用带多线程的 FFMPEG 解码 h264 文件时出错?

C++ - 如何安全地包装 malloc 或使用 new 运算符进行仿真