繁体   English   中英

C++ 中的临时对象在哪里分配?

[英]Where are temporary objects allocated in C++?

SomeClass a, b, c;
SomeClass foo();
SomeClass a = (b + c); //Where is the object (b + c) allocated?
SomeClass a = foo(); //Where is the returned value of foo() allocated?

我的猜测是它们是在堆上分配的,因为我读到临时对象在表达式(;)的末尾被销毁

这对我来说很有意义,因为可以通过窃取堆上临时对象的指针来实现移动构造函数。

如果完全创建(考虑优化),它们在自动存储中 即堆栈。

通常,如果临时对象有目的地,则可以在那里创建。 更强大的是,即使临时对象具有不同的类型,这也是正确的: Foo f = transmogrify(Bar()); - Bar()临时可能会窃取f所需的存储空间。

析构函数运行时有一个理论模型,但通常这不是可观察的行为,因此可以优化。 即许多 dtors 可以提前运行。

暂无
暂无

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

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