临时存储的时间要求是什么? [英] What's the requirement for storage duration of temporaries?

查看:101
本文介绍了临时存储的时间要求是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

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),必须保留至少到该块结束为止.

I can't deduce whether buffer in main is allowed to reuse the memory previously occupied by the temporary object of class Test. According to The Standard automatic storage (3.7.2/1) must persist for at least until the block ends.

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

I can't find phrasing that would force a temporary object to use automatic storage except 6.6/2 where a jump statement is described and says that on exit from a scope [...], destructors (12.4) are called for all constructed objects with automatic storage duration (3.7.2) (named objects or temporaries) which seems to imply that temporaries use automatic storage.

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

Are temporaries required to use automatic storage? Is the local variable in main in code above allowed to reuse the memory previously occupied by the temporary or should it use distinct storage?

推荐答案

临时项的生存期(除非绑定到const&)一直延伸到完整表达式的末尾.在您的情况下,main中的第一行.允许编译器重用相同的内存,但是是否使用是实现细节(即实现质量)

The lifetime of the temporary (unless bound to a const&) extends to the end of the full expression. In your case the first line in main. The compiler is allowed to reuse the same memory, but whether it does or not is an implementation detail (i.e. quality of implementation)

12.2 [class.temporary]

12.2 [class.temporary]

/3 [...]临时对象被销毁,这是评估的最后一步 [...]的完整表达式(1.9)(在词法上)包含创建它们的位置.[...]

/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在两个上下文中,临时变量在与完整表达式末尾不同的位置被销毁.第一个上下文是表达式作为定义对象的声明程序的初始化程序出现时. [...]

/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第二种情况是引用绑定到临时项时.

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

由于您也不例外,所以Test临时目录属于第一类,并且在第一行评估的最后一步被销毁.

Since you are in neither exception, the Test temporary falls into the first category and is destroyed as the last step of the evaluation of that first line.

这篇关于临时存储的时间要求是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆