Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/126.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 是否为临时对象的字段指定未定义的行为?_C++_Pointers_Memory Address_Temporary - Fatal编程技术网

C++ 是否为临时对象的字段指定未定义的行为?

C++ 是否为临时对象的字段指定未定义的行为?,c++,pointers,memory-address,temporary,C++,Pointers,Memory Address,Temporary,我用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-&g

我用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{int i;};
模板
T*获取地址(T&&T){return&T;}
从临时(S*const S)中作废打印值{
标准::cout i=0;
std::cout i=0;
行未定义的行为

s->i=0;
行是否是未定义的行为

否。将在完整表达式后销毁,其中包括执行函数体
print\u value\u from\u temporary
。对于
s->i=0;
中的
print\u value\u from\u temporary
临时尚未销毁

所有临时对象都将被销毁,这是计算完整表达式的最后一步,该表达式(词汇上)包含创建它们的点


这很好,因为对此类实例的访问不会超过对象的生存期(临时)。临时对象将一直处于活动状态,直到此行中的所有函数都完成,因此包括从临时对象中打印值。这种访问的有效性与对象是否为临时对象无关,而是与对象是否已销毁有关。