Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are variables local to a class that are not declared as pointers, created on the heap or stack?

Tags:

c++

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;
}
like image 745
Jimmyt1988 Avatar asked May 09 '15 23:05

Jimmyt1988


People also ask

Are pointers allocated on heap or stack?

Pointer is allocated on the stack and the object it is pointing to is allocated on the heap.

Are pointers stored in stack or heap in C?

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.

What variables are stored in stack and heap?

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.

Do you have to use pointers for heap variables?

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.


1 Answers

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.

like image 103
Alfred Rossi Avatar answered Nov 07 '22 06:11

Alfred Rossi