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?
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.
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.
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.
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.
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.
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