临时工的寿命

发布于 2024-10-03 07:15:35 字数 343 浏览 7 评论 0原文

下面的代码工作正常,但是为什么这个代码是正确的呢?为什么 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

享受孤独 2024-10-10 07:15:36

当词法上包含其计算创建临时对象的右值的完整表达式被完全计算时,临时对象将被销毁。让我用 ASCII 艺术来演示一下:

____________________   full-expression ranges from 'b' to last ')'
bar( foo().c_str() );
     ^^^^^          ^
       |            |
     birth       funeral

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:

____________________   full-expression ranges from 'b' to last ')'
bar( foo().c_str() );
     ^^^^^          ^
       |            |
     birth       funeral
寒尘 2024-10-10 07:15:36

$12.2/3-“临时对象是
作为最后一步被摧毁
评估完整表达式 (1.9)
(词汇​​上)包含点
他们被创造的地方。这是真实的
即使评估结果是
抛出异常。”

foo() 返回的临时变量的生命周期一直延伸到创建它的完整表达式的末尾,即直到函数调用“bar”的末尾。

编辑2:

$1.9/12-“完整表达式是
不是子表达式的表达式
的另一种表达方式。如果一种语言
构造被定义为产生一个
函数的隐式调用、使用
考虑语言结构
为目的的表达
这个定义。”

$12.2/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. This is true
even if that evaluation ends in
throwing an exception."

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:

$1.9/12- "A full-expression is an
expression that is not a subexpression
of another expression. If a language
construct is defined to produce an
implicit call of a function, a use of
the language construct is considered
to be an expression for the purposes
of this definition."

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文