2

(In C++) Will instantiating a class without using the new keyword cause its internal variables to be created on the stack, if they are defined using the new keyword inside the class's constructor, or will they be created on the heap?

In other words, if we have a class or struct that contains a variable (an array for example) defined inside its constructor using the new keyword, will creating an instance of this class without using new cause the internal array to be created on the stack, or the heap?

trincot
  • 317,000
  • 35
  • 244
  • 286
Mo Sanei
  • 445
  • 6
  • 22
  • possible duplicate of [Global memory management in C++ in stack or heap?](http://stackoverflow.com/questions/1169858/global-memory-management-in-c-in-stack-or-heap) – Suma Nov 15 '13 at 09:01
  • @Suma I think this is surely not a duplicate of [that](http://stackoverflow.com/q/1169858/2932052). – Wolf Nov 16 '13 at 07:58

5 Answers5

3

Operator new allocates memory in the heap unless you use the placement new operator where you can yourself point the memory used by the object.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • I think the core message should be better separated from the detailed descriptions of the alternative. – Wolf Nov 15 '13 at 08:51
3

Consider the following code and assume no optimizations:

struct Foo {
    int* pointer_to_int;

    Foo() : pointer_to_int(new int) { }
    ~Foo() { delete pointer_to_int; }
}

void func() {
    Foo some_foo;
    Foo* some_other_foo = new Foo;
}

some_foo will be allocated on the stack. The stack will grow by at least sizeof(Foo) (which will be at least enough space to store a pointer to an integer (sizeof(int*)).

some_other_foo is stored on the heap because of the use of new. Again, at least sizeof(Foo) will be allocated, but this time from the heap.

The int that is created in Foo's constructor will be stored on the heap in both cases. This will increase the size of the heap by at least sizeof(int).

chwarr
  • 6,777
  • 1
  • 30
  • 57
3

if we have a class or struct that contains a variable (an array for example) declared inside its constructor using the new keyword, will creating an instance of this class without using new cause the internal array to be created on the stack, or the heap?

yes, even if you create an object on stack (without new keyword) its internal data will be allocated on heap if new is used in class construcor (there might be exceptions when placement new is used to allocate data on stack - we'll see it later). Common example is allocating an array:

int main() {
    int* t = new int[100];  // pointer is on stack, data on the heap
    //...
}

and similarly:

class A{
public:
    A(){ 
        int* t = new int[100];
        std::cout<<"heap used\n";
        delete t;
    }
};

int main(int argc, char** argv) {

    A a1;
    // ...
}

prints:

heap used

and indeed, 100 ints have been allocated (and deleted) on the free store.


If you need to specify the memory location you can use placement new:

char buf[1024];
string* p = new (buf) string("on stack");  // pointer is on stack,
                                           // data on the stack
4pie0
  • 29,204
  • 9
  • 82
  • 118
  • 1
    You should be more precise: the **pointer to the object is placed on the stack**, not the object itself. – Wolf Nov 15 '13 at 08:43
  • 2
    what object? I am precise: pointer is on stack, data on the heap – 4pie0 Nov 15 '13 at 08:45
  • This *even if you create an object on stack* is misleading, I think. I refer to the text, not the code snippet. – Wolf Nov 15 '13 at 08:48
  • @WolfP. I might rewrite the answer, please just give me a hint what is misleading to you – 4pie0 Nov 15 '13 at 08:58
  • Cut the clause *even if you create an object on stack its internal data will be allocated on heap if new is used* and paste it **before the second example**, that will do, basically. – Wolf Nov 15 '13 at 09:06
0

In addition to

  • ordinary new (allocated on heap)
  • placement new syntax (with memory already allocated)

...there is another option to use new that does not necessarily involve heap usage, that's the customized allocation by overloading the operator new (and delete!).


Conclusion (edit comment)

So, even if created using new, objects can reside

  • on the heap (which is the default behaviour)
  • in an existing piece of memory that it is placed on (placement new syntax)
  • also anywhere else if the user wishes so (by overloading new)

The addresses returned by each of these new options can be stored everywhere in the address space of the calling process (stack, heap, or data segment).

Wolf
  • 9,679
  • 7
  • 62
  • 108
-1

Anything created with a new is created on the heap.

Instantiating a class without using new will stack-allocate the class object. However its data members may or may not be stack allocated according to how they are instantiated.

By the way, static variables within functions are also heap allocated; this is how they are able to persist values between function calls.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • 4
    `static` variables are *not* on the heap. They are statically allocated (given fixed addresses). – Alan Stokes Nov 15 '13 at 08:16
  • 1
    Initialized `static`variables go on the data segment and un-initialized ones go to .bss – HAL Nov 15 '13 at 08:18
  • @AlanStokes You are right,`static` variables are in data segment. – BlackMamba Nov 15 '13 at 08:20
  • @Alan Stokes, of course you're correct (therefore a respectful +1) but the point I'm making is that they are not stack allocated - a common misconception. – Bathsheba Nov 15 '13 at 08:22
  • Not everything created with new is created on the heap; placement new : `char buf[1024]; string* p = new (buf) string("hello"); cout << *p << endl;` – AndersK Nov 15 '13 at 08:25
  • So data members which are allocated using `new` in the class' constructor will be heap-allocated even if the object is created on the stack? – Mo Sanei Nov 15 '13 at 08:28
  • @Mohammad The pointer members will be on the stack and the objects they point to on the heap. – Alan Stokes Nov 15 '13 at 08:32