简体   繁体   English

临时物体的寿命

[英]Lifetime of temporary objects

I encountered the following code (roughly): 我遇到了以下代码(粗略地):

struct StringBuffer {
    StringBuffer(const char* string) {strcpy(m_buffer, string);}
    const char* c_str() const {return m_buffer;}
    char m_buffer[128];
};


std::string foobar() {
    const char* buffer = StringBuffer("Hello World").c_str();
    return std::string(buffer);
}

Am I correct in assuming that after the line: 假设在行之后我是否正确:

    const char* buffer = StringBuffer("Hello World").c_str();

buffer is pointing to a pointer in a deconstructed StringBuffer object? buffer指向解构的StringBuffer对象中的指针?

To answer your question at the end, yes, buffer will be a stray pointer. 要在最后回答你的问题,是的, buffer将是一个迷路指针。

To answer the more general question about lifetime of temporary values, I suggest you read this reference which says: 为了回答关于临时值的生命周期的更一般的问题,我建议你阅读这个参考文献说:

... all temporaries are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created... ...所有的临时演员都被摧毁,作为评估全曲面的最后一步(词法上)包含创建它们的点......

Which for your case means that once the assignment to buffer is done, the temporary object is destructed. 对于您的情况,这意味着一旦完成buffer的分配,就会破坏临时对象。

Yes. 是。

By convention, functions like std::string::c_str() aren't meant for caching because even if it pointed to a non-temporary object, it could be invalidated by a re-allocation of the string it points to. 按照惯例,像std :: string :: c_str()这样的函数不用于缓存,因为即使它指向非临时对象,它也可能通过重新分配它指向的字符串而失效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM