Temporary object的寿命延长

huangapple go评论62阅读模式
英文:

Lifetime extension of temporary object

问题

以下是翻译好的部分:

在#0处创建了一个prvalue,并传递给foo #1。
对象的生命周期被延长,然后传递给bar #2。此时,临时对象不会被延长两次吗?
Sanitizer没有报告任何问题。
此时我错过了什么?

英文:

There is the following piece of code

void bar(int  const & x) //#3
{
}

void foo(int  const &  x) //#1
{    
    bar(x); //#2
}

int main()
{
   double  x = 1.0;
   foo(static_cast<int>(x)); //#0    
}

At #0 a prvalue is created and it is passed to foo #1.
The lifetime of object is extended. Then it is passed to bar #2. At this point the temporary object is not extended twice?

Sanitizer does report any issue.

What I am missing at this point?

答案1

得分: 3

你在这里创建了一个临时对象:

foo(static_cast<int>(x)); //#0

这个临时对象的生命周期一直持续到这个表达式结束,也就是说一直到 foo 在这里返回之前。因为 foo 调用了 bar,所以 foo 不会在 bar 返回之前返回。因此,在这里没有必要延长临时对象的生命周期。

英文:

You create a temporary here:

foo(static_cast&lt;int&gt;(x)); //#0

The life-time of this temporary is until the end of this expression, which effectively means until foo returns here. Because foo calls bar, it doesn't return until bar does. Therefore, there is no need to extend the life-time anywhere here.

huangapple
  • 本文由 发表于 2023年5月17日 16:24:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76269986.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定