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

后端 未结 9 1336
既然无缘
既然无缘 2020-12-28 08:58

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 thou

9条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-28 08:59

    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.

    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.

提交回复
热议问题