gpt4 book ai didi

c++ - 临时元素的保存期限有什么要求?

转载 作者:太空狗 更新时间:2023-10-29 19:46:48 25 4
gpt4 key购买 nike

考虑以下代码:

class Test() {
public:
Test()
{
memset( buffer, 0, sizeof( buffer ) );
}
void Process()
{
printf( buffer );
}
private:
char buffer[1000];
};

int main()
{
Test().Process();
char buffer[1000] = {};
print( buffer );
return 0;
}

无法推断main中的buffer是否允许重用之前被class Test的临时对象占用的内存。根据标准自动存储(3.7.2/1)must persist for at least until the block ends .

我找不到强制临时对象使用自动存储的措辞,但 6.6/2 除外,其中描述了跳转语句并说从作用域退出时 [...],析构函数 (12.4)为所有具有自动存储持续时间 (3.7.2) 的构造对象(命名对象或临时对象)调用,这似乎暗示临时对象使用自动存储。

使用自动存储是否需要临时文件?上面代码中 main 中的局部变量是否允许重用之前被临时占用的内存,还是应该使用不同的存储?

最佳答案

临时变量的生命周期(除非绑定(bind)到 const&)延伸到完整表达式的末尾。在您的例子中,main 中的第一行。允许编译器重用相同的内存,但是否重用是实现细节(即实现质量)

12.2 [class.temporary]

/3 [...] Temporary objects are destroyed as the last step in evaluating the full-expression (1.9) that (lexically) contains the point where they were created.[...]

/4 There are two contexts in which temporaries are destroyed at a different point than the end of the full expression. The first context is when an expression appears as an initializer for a declarator defining an object. [...]

/5 The second context is when a reference is bound to a temporary.

由于您都没有异常(exception),Test 临时文件属于第一类,并且在第一行求值的最后一步被销毁

关于c++ - 临时元素的保存期限有什么要求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7118323/

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