加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 临时存储时间的要求是什么?

发布时间:2020-12-16 10:19:56 所属栏目:百科 来源:网络整理
导读:请考虑以下代码: class Test() {public: Test() { memset( buffer,sizeof( buffer ) ); } void Process() { printf( buffer ); }private: char buffer[1000];};int main(){ Test().Process(); char buffer[1000] = {}; print( buffer ); return 0; } 我无法
请考虑以下代码:

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

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

我无法推断主要的缓冲区是否允许重用以前由类Test的临时对象占用的内存.根据标准自动存储(3.7.2 / 1)must persist for at least until the block ends.

我找不到强制临时对象使用自动存储的措辞,除了6.6 / 2,其中描述了一个跳转语句,并说在退出范围[…]时,所有构造对象都会调用析构函数(12.4)具有自动存储持续时间(3.7.2)(命名对象或临时对象),这似乎意味着临时使用自动存储.

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

解决方法

临时的生命周期(除非绑定到const&)延伸到完整表达式的末尾.在你的情况下,主要的第一行.允许编译器重用相同的内存,但它是否具有实现细节(即实现的质量)

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.

由于您既不是例外,Test临时属于第一类,并且作为第一行评估的最后一步被销毁.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读