gpt4 book ai didi

c++ - 当分配给 const 时,C++ 的生命周期暂时延长到词法

转载 作者:搜寻专家 更新时间:2023-10-31 00:40:28 24 4
gpt4 key购买 nike

<分区>

我最近惊讶地发现 C++ 中的一个临时变量被提升为具有完整的词法范围:

class Foo {
public:
Foo() {
std::cout << "A";
}
~Foo() {
std::cout << "B";
}
};

int main(void)
{
// Prints "ACB", showing the temporary being promoted to having lexical scope.
const Foo& f = Foo();
std::cout << "C";
return 0;
}

除了将临时对象分配给引用的可疑行为之外,这实际上工作得很好(在 VS2010 和 G++ v4.1 中测试)。输出为 ACB ,清楚地表明临时对象已提升为具有词法范围,并且仅在函数结束时被破坏( BC 之后打印)。


其他临时变量不会这样:

int main(void)
{
// Prints "ACBD", showing that the temporary is destroyed before the next sequence point.
const int f = ((Foo(), std::cout << "C"), 5);
std::cout << "D";
return 0;
}

根据我的代码注释,这会打印出 ACBD ,表明临时变量一直保留到整个表达式完成计算(为什么 CB 之前打印),但在下一个序列点之前仍然被销毁(为什么 BD 之前打印)。 (这种行为是我认为 C++ 中所有临时变量的工作方式。我对早期的行为感到非常惊讶。)

有人可以解释什么时候将临时对象提升为具有这样的词法范围是合法的吗?

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