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?
In C++, you can allocate primitive types on the heap if you want to:
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++:
This will allocate
myObjecton the stack. Note thatnewis rarely used in modern C++.Furthermore, you can overload
operator new(either globally or class-specific) in C++, so even if you saynew MyClass, the object does not necessarily get allocated on the heap.