-1
class Foo {
    int num;
};

class Bar {
public:
    Bar() {
       Foo f1;
    }
};

int main() {
    Bar* b = new Bar();
    return 0;
}

In the code above, I create an instance of Bar (b) on the heap. In the constructor of Bar, an instance of Foo (f1) is created. Since b is created on the heap, and f1 is temporary, I'm not sure - where is it stored when the constructor gets called?

Objects memory is handled automatically when stored on the stack, so if f1 is stored on the heap, how is it destructed automatically when the constructor of Bar is finished? On the other hand, if it is stored on the stack, how does the object b on the heap points to it?

SubMachine
  • 487
  • 3
  • 11

2 Answers2

2

The storage of the object pointed to by b — that is, the object of type Bar — is allocated on the heap.

However, f1 isn’t part of that object. Instead, it’s a local object that’s created when a function is called (the function being the constructor to Bar, but that’s irrelevant). And local objects are all allocated on the call stack, without exception.

(Nathan’s answer correctly points out that C++ doesn’t have a concept of stack or heap storage; the explanation above concerns implementations of C++, not the language definition.)

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
2

C++ doesn't have a concept of stack and heap memory space. Instead, it has automatic storage duration and dynamic storage duration. Things that have automatic storage duration (you did not use new) get cleaned up when the scope is left/parent object is destroyed. Dynamic storage objects are only cleaned up when you manually release the memory you acquired for it.

In this case, since you do not call delete on b to release the memory then the object b points to is not destroyed, so you have a memory leak.

With

Bar() {
   Foo f1;
}

You create an object in the constructor, and once the constructor body exits the compiler will insert code to clean up f1 for you, as it has automatic storage duration.


If you create an object with dynamic storage duration, and that object has sub objects that have automatic storage duration, then they still reside in the same memory space allocated for the main object. As long as the main object is properly released, then its destructor will handle cleaning up the sub objects inside it that have automatic storage duration.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • 1
    *C++* doesn’t have a concept of heap and stack, but *implementations* do. And this seems to be what OP is asking about. – Konrad Rudolph Jan 26 '21 at 13:22