简体   繁体   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?

My guess is that they are allocated on the heap because I read that temporary objects are destroyed at the end of the expression(;).我的猜测是它们是在堆上分配的,因为我读到临时对象在表达式(;)的末尾被销毁

It makes sense to me because the move constructor could be implemented by stealing the pointer of the temporary object on the heap.这对我来说很有意义,因为可以通过窃取堆上临时对象的指针来实现移动构造函数。

If created at all (consider optimizations), they're in automatic storage .如果完全创建(考虑优化),它们在自动存储中 Ie the stack.即堆栈。

Generally, if there's a destination for the temporary object, it can be created there.通常,如果临时对象有目的地,则可以在那里创建。 Even stronger, that can be true even if the temporary has a different type: Foo f = transmogrify(Bar());更强大的是,即使临时对象具有不同的类型,这也是正确的: Foo f = transmogrify(Bar()); - the Bar() temporary can probably steal the storage needed for f . - Bar()临时可能会窃取f所需的存储空间。

There's a theoretical model when destructors run, but often that's not observable behavior and therefore optimizable.析构函数运行时有一个理论模型,但通常这不是可观察的行为,因此可以优化。 Ie many dtors can run early.即许多 dtors 可以提前运行。

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

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