Constructor on stack [closed]
When constructor is called do we push it on stack, if yes then when it gets popped from that?
When a constructor (or other function) is called, the calling address is pushed on the stack. It's popped off the stack when the function returns. The function itself (constructor or otherwise) isn't pushed on the stack.
This, of course, assumes the code for the function hasn't been generated inline -- in which case there's no call and no return, and probably no stack usage at all.
If you create an object on the stack it will be popped/deleted when you exit that stack frame / scope.
A constructor gets called to build a class wherever it happens to be. If you write something like:
{
Foo f;
...
}
Then Foo has local scope and will be allocated on the stack, and then constructed there. If you write something like:
new Foo f;
then Foo will be allocated on the heap, and will then be constructed there. The first Foo will be destructed and then popped off the stack when the thread of execution leaves the enclosing scope (the curly brackets). The second Foo will be destructed and freed when you call delete on it.
精彩评论