有一条规则说明std :: tuple的成员被破坏了吗?
例如,如果Function1返回一个std::tuple<std::unique_ptr<ClassA>, std::unique_ptr<ClassB>>to Function2,那么我可以确定(当Function2剩下的范围时)ClassB第二个成员ClassA引用的实例在第一个成员引用的实例之前被销毁吗?
std::tuple< std::unique_ptr< ClassA >, std::unique_ptr< ClassB > > Function1()
{
std::tuple< std::unique_ptr< ClassA >, std::unique_ptr< ClassB > > garbage;
get<0>(garbage).reset( /* ... */ );
get<1>(garbage).reset( /* ... */ );
return garbage;
}
void Function2()
{
auto to_be_destroyed = Function1();
// ... do something else
// to_be_destroyed leaves scope
// Is the instance of ClassB destroyed before the instance of ClassA?
}
Run Code Online (Sandbox Code Playgroud) 为什么用auto关键字定义变量不带有constexpr用于初始化它的表达式的“性质”?
例如,请考虑以下代码:
#include <string_view>
constexpr std::string_view f() { return "hello"; }
static constexpr std::string_view g() {
constexpr auto x = f(); // (*)
return x.substr(1, 3);
}
int foo() { return g().length(); }
Run Code Online (Sandbox Code Playgroud)
使用 GCC 10.2 和--std=c++20 -fsanitize=undefined -O3,编译为:
foo():
mov eax, 3
ret
Run Code Online (Sandbox Code Playgroud)
但是,如果我们删除 (*) 行上的 constexpr,我们将得到一个 27 行的程序,其中包含一堆指针、一个长字符串常量等。
笔记:
autowrt constexprness的一般行为。该示例只是表明 GCC 不会将 x 视为constexpr我们没有明确告诉它。