【发布时间】:2013-01-20 12:15:33
【问题描述】:
最近我惊讶地发现 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,清楚地表明临时对象已被提升为具有词法范围,并且仅在函数结束时被破坏(B在C之后打印)。
其他临时变量不这样:
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,表明临时变量会一直保留到整个表达式完成评估(为什么C 在B 之前打印),但仍会在下一个序列点之前被销毁(为什么B 在D 之前打印)。 (这种行为是我认为 C++ 中所有临时变量的工作方式。我对之前的行为感到非常惊讶。)
谁能解释一下什么时候将临时对象提升为具有这样的词法范围是合法的?
【问题讨论】:
-
仅当您将其绑定到第一个示例中的引用时。 (
const&和&&引用都有效) -
见 GoTW - herbsutter.com/2008/01/01/…