开发者

Constructor on stack [closed]

开发者 https://www.devze.com 2023-02-22 19:28 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad开发者_运维知识库, or rhetorical andcannot be reasonably answered in its current for
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad开发者_运维知识库, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号