简体   繁体   中英

Could be an object created on the heap treated as 'being on stack' in C++?

Have the code:

struct FooBar
{
  FooBar()
  {
    MyObject obj;

    /// when c-tor is ended, obj must be deleted through d-tor call
  }
};
...
FooBar* fooBar(new FooBar);

fooBar is allocated on the heap. But object MyObject obj inside FooBar 's constructor does not know where it is created. So could be MyObject instantiation in the context of FooBar treated like it was created in the stack?

Does object allocated on the heap have its own stack? What is the size of such stack?

obj is allocated on the stack in your example (the "ordinary" stack, the "same" that is used in the code that calls new FooBar - assuming your environment has a stack to begin with).

The fact that this points to somewhere on the heap doesn't change the fact that the constructor is a (relatively) ordinary function call, and uses the same stack as other functions.

C++ does not know about stack or heap. It does know about objects with automatic and dynamic storage duration. In your case, fooBar has dynamic storage duration (because it is created using new ). It will live until you call delete on it. obj has automatic storage duration (because it is not created using new ). Its lifetime ends when the enclosing function (the FooBar -constructor) ends.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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