分配给临时对象未定义行为的字段吗?

Is assigning to a field of temporary object undefined behavior?

我使用带有 -O1-std=c++20 标志的 gcc 和 clang 编译了以下代码,它似乎按预期工作。

#include <iostream>

struct S { int i; };

template<typename T>
T *get_address(T&& t) { return &t; }

void print_value_from_temporary(S *const s) {
    std::cout << s->i << '\n';
    s->i = 0;
    std::cout << s->i << '\n';
}

int main() {
    print_value_from_temporary(get_address(S{42}));
}

我的问题是:s->i = 0; 行是未定义的行为吗?

Is the s->i = 0; line an undefined behavior?

没有。 temporary 将在完整表达式之后被销毁,其中包括 print_value_from_temporary 的函数体的执行。对于 print_value_from_temporary 中的 s->i = 0;,临时文件尚未被销毁。

All temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created,