does the new operator always malloc (in the heap) or can it something alloca (in the stack)

Assume we have a context

1
2
3
4
{
  some_class some_object = new ...
  variable = some_object.do_stuff()//variable exists outside the context
}


assuming that some_class is trivial enough, would the new operator call alloca instead of malloc

if that can never happen, what is the way to explicitly construct an object in the stack
Last edited on
Assume that you have error in the example. Should be:
1
2
3
4
5
{
  some_class* some_pointer = new some_class /*initializer*/ ;
  variable = some_pointer->do_stuff();
  delete some_pointer;
}

The some_pointer is an object in the stack. It is a pointer, which stores address of some other object.

If you want object in stack, then:
1
2
3
4
{
  some_class some_object /*initializer*/;
  variable = some_object.do_stuff();
}

assuming that some_class is trivial enough, would the new operator call alloca instead of malloc
Probably not. The new'ed object has to stick around until it's deleted, which might be long after the calling function returned and popped the stack. There might be some cases where the compiler knows that the object is deleted when the function returns and could therefore make this optimization, but I don't know if any of them do.
Registered users can post here. Sign in or register to post.