Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does new always allocate on the heap in C++ / C# / Java

My understanding has always been, regardless of C++ or C# or Java, that when we use the new keyword to create an object it allocates memory on the heap. I thought that new is only needed for reference types (classes), and that primitive types (int, bool, float, etc.) never use new and always go on the stack (except when they're a member variable of a class that gets instantiated with new). However, I have been reading information that makes me doubt this long standing assumption, at least for Java and C#.

For example, I just noticed that in C# the new operator can be used to initialize a value type, see here. Is this an exception to the rule, a helper feature of the language, and if so, what other exceptions would there be?

Can someone please clarify this?

like image 825
Alex Avatar asked Aug 07 '11 10:08

Alex


People also ask

Does new always allocate on the heap?

Note that new is rarely used in modern C++. Furthermore, you can overload operator new (either globally or class-specific) in C++, so even if you say new MyClass , the object does not necessarily get allocated on the heap.

When should I allocate on the heap?

If you need to control manually the lifetime of the object, allocate it on the heap. If the object is big and the stack is not big enough for it, allocate it on the heap.

What happens if you call new but the heap is out of memory?

From "New and delete (C++)" on Wikipedia: If not enough memory is available in the free store for an object of type T , the new request indicates failure by throwing an exception of type std::bad_alloc . This removes the need to explicitly check the result of an allocation.

What goes on the heap in C?

The heap is a large pool of memory that can be used dynamically – it is also known as the “free store”. This is memory that is not automatically managed – you have to explicitly allocate (using functions such as malloc), and deallocate (e.g. free) the memory.


1 Answers

I thought that new is only needed for reference types (classes), and that primitive types (int, bool, float, etc.) never use new

In C++, you can allocate primitive types on the heap if you want to:

int* p = new int(42);

This is useful if you want a shared counter, for example in the implementation of shared_ptr<T>.

Also, you are not forced to use new with classes in C++:

void function()
{
    MyClass myObject(1, 2, 3);
}

This will allocate myObject on the stack. Note that new is rarely used in modern C++.

Furthermore, you can overload operator new (either globally or class-specific) in C++, so even if you say new MyClass, the object does not necessarily get allocated on the heap.

like image 104
fredoverflow Avatar answered Oct 06 '22 04:10

fredoverflow