对临时对象的 R 值引用不会出现段错误

R-value reference to a temporary object does not segfault

我正在复习 我正在尝试自己的东西以了解我的理解。在答案中,作者在

行中说

auto&& __range=exp;

Your exp creates a temporary object, then returns a reference to within it. The temporary dies after that line, so you have a dangling reference in the rest of the code.

我对这一行的理解是: S() returns a temporary object of type S and .func() on it is返回对此临时对象的引用。变量 __range 指向一个不存在的位置,因为类型 S 的对象在该行的末尾被销毁。

所以我写了一个类似的程序(如下)并进行了一些修改,并期望它出现 SEGFAULT,但它根本没有出现 SEGFAULT。

#include <iostream>
#include <string>
#include <map>
using namespace std;

struct S
{
    map<int, int> m;

    S()
    {
        m[24] = 5;
    }

    const int &func() const
    {
        return m.find(24)->second;
    }
};

int main()
{
    auto &&x = S().func();
    std::cout<<"\n value is "<<x;

    return 0;
}

我不确定我理解上的差距。帮帮我。提前致谢。

如果您使用地址清理器构建程序,您将获得:

SUMMARY: AddressSanitizer: heap-use-after-free

在这一行:

uto &&x = S().func();

内存问题可能不会立即使您的程序崩溃,但它们可能会在其他函数或其他线程上使长时间运行的 运行 程序崩溃,从而导致非常奇怪的崩溃情况。

was expecting it to SEGFAULT

那是错误的。 C++ 语言在任何情况下都不能保证出现段错误。事实上,段错误的概念对于语言本身来说是完全陌生的。

根据 C++ 语言,您的程序的行为是未定义的。这意味着任何事情都可能发生。段错误可能会发生,但不能保证一定会发生。对程序的行为没有任何保证。