A simple example how an object can be constructed on stack is an implicit use of operator new
in the non-allocating form, void* operator new (std::size_t size, void* ptr) throw()
:
class Foo {
public:
Foo();
Foo(const Foo &);
~Foo();
private:
// data members
...
}
void bar() {
Foo f1;
// // Allocate sufficient memory on stack:
// char f1[sizeof(Foo)];
// // Call operator new on this memory and execute Foo's constructor
// // with (this == f1):
// operator new (sizeof(Foo),f1) Foo();
...
// Or «non-optimized» case, with copy-constructor involved:
Foo f2 = Foo();
// char f2[sizeof(Foo)];
// {
// // tmp is constructed as in the previous case:
// char tmp[sizeof(Foo)];
// operator new (sizeof(Foo),tmp) Foo();
// // And then f2 is constructed using Foo's copy-constructor:
// Foo::Foo(f2 /*this*/, tmp)
// }
// // Here, tmp must be destructed and popped from stack.
}
Links: