Take the following:
A a;
class B; // No content for brevity
class A
{
public:
A()
{
b.SetTitle("hi");
}
private:
B b;
}
int main()
{
return 0;
}
The question here is if b
which is declared inside A
is declared on the heap or on the stack.
If on the heap, does this mean it is automatically deleted or must i also delete this too?
Side question:
This is what i was originally doing but thought i was being a bit stupid as i had to keep declaring everything as new everywhere.. if the above is on the stack, i guess it wasn't so stupid right?
A a;
class B; // No content for brevity
class A
{
public:
A()
{
this->b( new B() ); // I don't have C++ 14 :( so i can't do make_unique
b->SetTitle("hi");
}
private:
unique_ptr<B> b;
}
int main()
{
return 0;
}
Pointer is allocated on the stack and the object it is pointing to is allocated on the heap.
Pointers can be stored on the stack, the heap, or be statically allocated. The objects they point to can be stored on the stack, the heap, or statically as well.
Stack memory only contains local primitive variables and reference variables to objects in heap space. Objects stored in the heap are globally accessible whereas stack memory can't be accessed by other threads.
Pointing to the heap in C/C++ If you want to put something on the heap, you need to speak up and put it there. You also need to keep track of your data using a pointer. A pointer is a memory address. In C/C++, you use an asterisk * to create a pointer.
It still could be either or even (as Thomas Matthews points out below) in a fixed memory block. In this case you can think of it as "inside of A". If you put A on the heap it's on the heap. If you allocate "A" at the top of a function, say, it's on the stack (but inside of A).
Written like this it is a part of A and its lifetime is tied to A. You only need to worry about managing A.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With