【发布时间】:2021-09-27 17:25:39
【问题描述】:
正如您在 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都引用了对应的临时对象,仍然Clang和GCC只延长其中一个临时对象的生命周期,并没有就哪一个达成一致:https://gcc.godbolt.org/z/onWKaq8MG
这两个编译器是否都在他们的权利范围内,或者其中一个编译器(或两者)行为不正确?
【问题讨论】:
标签: c++ object-lifetime temporary-objects