gpt4 book ai didi

c++ - 是否分配给临时对象未定义行为的字段?

转载 作者:行者123 更新时间:2023-12-03 23:58:06 25 4
gpt4 key购买 nike

我使用 gcc 和带有 -O1-std=c++20 标志的 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 的函数体的执行。对于 s->i = 0; 中的 print_value_from_temporary 暂时还没有被销毁。

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

关于c++ - 是否分配给临时对象未定义行为的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67535958/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com