临时工的寿命
下面的代码工作正常,但是为什么这个代码是正确的呢?为什么 foo() 返回的临时变量的“c_str()”指针有效?我想,当输入 bar() 时,这个临时文件已经被销毁了 - 但它似乎不是这样的。所以,现在我假设 foo() 返回的临时值将在调用 bar() 之后被销毁 - 这是正确的吗?为什么?
std::string foo() {
std::string out = something...;
return out;
}
void bar( const char* ccp ) {
// do something with the string..
}
bar( foo().c_str() );
The following code works fine, but why is this correct code? Why is the "c_str()" pointer of the temporary returned by foo() valid? I thought, that this temporary is already destroyed when bar() is entered - but it doesn't seem to be like this. So, now I assume that the temporary returned by foo() will be destroyed after the call to bar() - is this correct? And why?
std::string foo() {
std::string out = something...;
return out;
}
void bar( const char* ccp ) {
// do something with the string..
}
bar( foo().c_str() );
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当词法上包含其计算创建临时对象的右值的完整表达式被完全计算时,临时对象将被销毁。让我用 ASCII 艺术来演示一下:
A temporary object is destroyed when the full-expression that lexically contains the rvalue whose evaluation created that temporary object is completely evaluated. Let me demonstrate with ASCII art:
foo() 返回的临时变量的生命周期一直延伸到创建它的完整表达式的末尾,即直到函数调用“bar”的末尾。
编辑2:
The lifetime of the temporary returned by foo() extends until the end of the full expression where it is created i.e. until the end of the function call 'bar'.
EDIT 2: