英文:
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<int>(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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论