如您所知,在 C++ 中,如果临时对象绑定到本地引用,则临时对象的生命周期会延长到作用域结束。
但是如果使用临时或其他操作执行强制转换会发生什么,例如:
#include <iostream>
struct S
{
virtual ~S() { std::cout << "~S() "; }
};
struct U : S {};
int main()
{
// this temporary is destroyed in this line in GCC, and at the end in Clang
[[maybe_unused]] auto && u = dynamic_cast<const U&>( static_cast<const S&>( U{} ) );
std::cout << ". ";
// this temporary is destroyed in this line in Clang, and at the end in GCC
[[maybe_unused]] auto && s = *&static_cast<const S&>( S{} );
std::cout << ". ";
}
这清楚地看到,u
并s
参考相应的临时对象,还是锵和GCC延长只有临时对象之一的寿命,并且不同意哪一个:https://gcc.godbolt.org/z/onWKaq8MG
两个编译器是否都在他们的权利范围内,或者其中一个(或两个)编译器的行为不正确?
我认为 Clang 是正确的。
- 没有用户定义的转换的 const_cast、static_cast、dynamic_cast 或 reinterpret_cast 转换将这些表达式之一转换为泛左值指的是操作数指定的对象,或其完整对象或其子对象(显式转换表达式被解释为作为这些演员的序列),
这里没有发生用户定义的转换,应该延长生命周期。
对于第二种情况,表达式*&...
不包括在延长生命周期的情况下,临时应在完整表达式之后立即销毁。
顺便说一句:Gcc 似乎与dynamic_cast
only 的行为不同。改变dynamic_cast
在第一情况下static_cast
,reinterpret_cast
或c风格转换寿命得到延长。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句