Difference between new operator in C++ and new operator in java

后端 未结 5 1338
粉色の甜心
粉色の甜心 2020-12-09 06:06

As far as I know, the new operator does the following things: (please correct me if I am wrong.)

  1. Allocates memory, and then returns the reference
5条回答
  •  渐次进展
    2020-12-09 06:48

    • In C++, T * p = new T;...
    1. allocates enough memory for an object of type T,

    2. constructs an object of type T in that memory, possibly initializing it, and

    3. returns a pointer to the object. (The pointer has the same value as the address of the allocated memory for the standard new, but this needn't be the case for the array form new[].)

    In case the memory allocation fails, an exception of type std::bad_alloc is thrown, no object is constructed and no memory is allocated.

    In case the object constructor throws an exception, no object is (obviously) constructed, the memory is automatically released immediately, and the exception is propagated.

    Otherwise a dynamically allocated object has been constructed, and the user must manually destroy the object and release the memory, typically by saying delete p;.

    The actual allocation and deallocation function can be controlled in C++. If there is nothing else, a global, predefined function ::operator new() is used, but this may be replaced by the user; and if there exists a static member function T::operator new, that one will be used instead.

    • In Java it's fairly similar, only that the return value of new is something that can bind to a Java variable of type T (or a base thereof, such as Object), and you must always have an initializer (so you'd say T x = new T();). The object's lifetime is indeterminate, but guaranteed to be at least as long as any variables still refer to the object, and there is no way to (nor any need to) destroy the object manually. Java has no explicit notion of memory, and you cannot control the interna of the allocation.

    Furthermore, C++ allows lots of different forms of new expressions (so-called placement forms). They all create dynamic-storage objects which must be destroyed manually, but they can be fairly arbitrary. To my knowledge Java has no such facilities.


    The biggest difference is probably in use: In Java, you use new all the time for everything, and you have to, since it's the one and only way to create (class-type) objects. By contrast, in C++ you should almost never have naked news in user code. C++ has unconstrained variables, and so variables themselves can be objects, and that is how objects are usually used in C++.

提交回复
热议问题