gpt4 book ai didi

c++ - 使临时变量的 const 引用成员安全吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:13:11 25 4
gpt4 key购买 nike

我曾多次尝试这样编写代码:

struct Foo
{
double const& f;
Foo(double const& fx) : f(fx)
{
printf("%f %f\n", fx, this->f); // 125 125
}

double GetF() const
{
return f;
}
};
int main()
{
Foo p(123.0 + 2.0);
printf("%f\n", p.GetF()); // 0
return 0;
}

但它根本不会崩溃。我还使用 valgrind 来测试程序,但没有出现错误或警告。因此,我假设编译器自动生成了一段代码,将引用指向另一个隐藏变量。但我真的不确定。

最佳答案

不,这不安全。更准确地说,这是 UB , 意味着一切皆有可能。

当您将 123.0 + 2.0 传递给 Foo 的构造函数时,将构造一个临时的 double 并绑定(bind)到参数 外汇。临时变量将在完整表达式(即 Foo p(123.0 + 2.0);)之后被销毁,然后引用成员 f 将变为悬挂。

请注意 temporary's lifetime不会延长到引用成员 f 的生命周期。

In general, the lifetime of a temporary cannot be further extended by "passing it on": a second reference, initialized from the reference to which the temporary was bound, does not affect its lifetime.

根据标准,[class.base.init]/8

A temporary expression bound to a reference member in a mem-initializer is ill-formed. [ Example:

struct A {
A() : v(42) { } // error
const int& v;
};

— end example ]

关于c++ - 使临时变量的 const 引用成员安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45385433/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com