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

后端 未结 5 1327
粉色の甜心
粉色の甜心 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:40

    The new keyword The new operator is somewhat similar in the two languages. The main difference is that every object and array must be allocated via new in Java. (And indeed arrays are actually objects in Java.) So whilst the following is legal in C/C++ and would allocate the array from the stack...

     // C/C++ : allocate array from the stack
        void myFunction() {
          int x[2];
          x[0] = 1;
          ...
        }
    

    ...in Java, we would have to write the following:

    // Java : have to use 'new'; JVM allocates
    //        memory where it chooses.
    void myFunction() {
      int[] x = new int[2];
      ...
    }
    

    ref:https://www.javamex.com/java_equivalents/new.shtml

提交回复
热议问题