Comparison of pointers and references of c ++/java/c # programming languages

Source: Internet
Author: User
Tags java reference

Some time ago, in my blog on cnblogs, I talked about:

References/pointers in java are not similar to references/pointers in c ++/C.

Java reference, equivalent to c ++ pointer (fun3 ). Java references can be assigned null values, while c ++ references (see fun2) cannot be assigned null values. c ++ pointers can be assigned null values (fun3 ).

In Java, there is no syntax for c ++ reference (fun2.

 

The results raised unnecessary questions. I write a blog to compare and reference the pointers and references of c ++/java/c # programming languages, hoping to attract more people, pay attention to this.

In terms of syntax, the pointers and references of C ++ are the most complex among the three development languages. Therefore, the following examples start with C ++ code, then compare it with the java/c # syntax.

 

1) C ++ simple type variables, including direct variable definition, pointer definition, and reference definition.

    int aa = 10;//c++    int &bb = aa;//c++    int *cc = &aa;//c++

The above three lines of code point the last three variables to the same data. In comparison, java/c # Only has variable definitions, and does not have reference definitions or pointer definitions. Note: Thanks to xiaotie and feilang, pointers exist in C #. In the unsafe state, pointers can be defined and used. Special correction.

 

2) C ++ function call parameters, simple type variables, including direct variable definition, pointer definition, and reference definition. The last two parameters change data within the function and exit the function, you can see the changed data.

void simple_by_val(int a, const int b){    a=15;    //b=13;            //error C2166: l-value specifies const object    //a=NULL;        //good    //b=NULL;        //error C2166: l-value specifies const object}void simple_by_ref(int &a, const int &b){    a=25;    //b=23;            //error C2166: l-value specifies const object    //a=NULL;            //good    //b=NULL;        //error C2166: l-value specifies const object}void simple_by_pointer(int *a, const int *b){    *a = 35;    //*b = 33;        //error C2166: l-value specifies const object    a = NULL;        //ok    b = NULL;        //ok}

Java does not have so many names, and only has direct variable definitions. C # is a little more complex, with references and out parameters.

        static void M(int a, ref int b, out int c)        {            c = 13;        }

In comparison, the function parameters of C # (ref int B), similar to the function parameters of C ++ (int & a), are the initial values before calling the function, change the data in the function and exit the function to view the changed data.

C # (out int c) has no corresponding syntax in C ++/Java. This operation does not assign an initial value before calling the function. This syntax is rarely seen before C #. It is only seen in some database stored procedures and function definitions. It is estimated that the syntax is copied from the database programming syntax.

Special note: Reference of C # (ref int B). It is only used in the definition of function parameter variables and cannot be used in local variables within the function. The reference (int & a) in C ++ can be used in local variables within the function.

 

3) the class object variable definition Syntax of C ++ is complex. It can be defined on a stack (without new) or heap (with new ).

    CMyClass obj;                        //stack    CMyClass *p2 = new CMyClass();        //heap

Java/C # is not so complex. It can be considered as the above two "synthesis + simplification.

 

4) in java/C #, the following usage is incorrect and a null pointer exception is reported. However, it is valid in C ++.

    CMyClass obj;    obj.run();

In C ++,

CMyClass obj;

The above code has called the constructor and completed variable initialization. In java/C #, this line of code is equivalent:

CMyClass obj = null;

 

5) in C ++, the stack variable has a function range and the memory is automatically recycled. The heap variable must be manually deleted.

In java/C #, variables are automatically recycled when they are idle (theoretically). If the variable is out of the scope, the memory is recycled.

 

{CMyClass obj; // stack obj. test () ;}// here, the stack variable is automatically deleted, and the memory is automatically recycled {CMyClass * p2 = new CMyClass (); // heap p2-> test ();} // here, the p2 variable is out of the scope of the variable. The p2 variable cannot be used below, but the memory is not released and Memory leakage occurs.

 

 

 

 

6) The following code is correct in C ++ and is incorrect in java/C. In the java/C # syntax, if no variable is defined and * is added, you cannot use-> to call a class function or a class member variable, or use delete.

 

CMyClass *p1 = null;CMyClass *p2 = new CMyClass();p2->ab();delete p2;p2 = null;

 

 

7) the following code is correct in the java/C # syntax and incorrect in C ++. In C ++, the pointer (CMyClass * p1 = null;) is used for this assignment ;).

CMyClass p1 = null;CMyClass p2 = new CMyClass();

 

8) the following code calls the "copy constructor" and "equal sign overload function" in the C ++ code ". These two functions are automatically generated by the compiler by default in C ++.

// C ++
CMyClass obj; // call the constructor CMyClass obj2 = obj; // call the copy constructor obj2 = obj; // call = Operator overload Function

The above code is roughly equivalent to cloning "clone" in java/C ". But more concealed (beginners do not know to call C ++ constructor, copy constructor, = Operator overload function), more complex. Java/C # overload functions without operators.

//C#            CMyClass obj = new CMyClass();            CMyClass obj2 = (CMyClass)obj.Clone();

In C #, the Clone function is not automatically generated. In Java, you can call super. clone () ---- the Java base class Object has a clone function by default.

In C ++, by default, the compiler automatically generates "copy constructor" and "equals number overload function,Many problems may occur..

In C ++, do not use CMyClass for function return values, which may cause unnecessary calls to "copy constructor" and "equal to number overload function". Do not return references to CMyClass &, reference of local variables in the function. It cannot be used after exiting the function. Return the pointer CMyClass * (preferably the pointer variable wrapped with a smart pointer ). Many beginners do not understand this.

Except std: string of C ++. Std: the "copy constructor" and "equal to number overload function" of string are optimized. The copied variables use the same char [] array internally as the copied variables, the char [] array is copied into two copies only when a string variable is changed. Std: string's "copy constructor" has no performance loss and reduces memory leakage than the string pointer. Therefore, for std: string, use object variables, object references, and object copy whenever possible to avoid using std: string pointers.

In addition, the String variable of java/C # cannot be changed (for example, the java StringBuilder class is variable), and the string variable of C ++ can be changed. Many people do not understand this subtle difference.

 

9) C ++ reference syntax, which is something Java/C # programmers do not know:

// C ++ CMyClass & a1; // error. Initialization is required when C ++ references the variable definition. // Java/C # When the variable definition is not required, it is necessary to initialize CMyClass & a1 = NULL; // error. The reference variable C ++ cannot assign a value to nullCMyClass & a1 = new CMyClass (); // error, C ++ reference variables cannot be assigned to a new object. In this case, the C ++ pointer is used. // The following C ++ code is correct: CMyClass a; CMyClass & a1 = a; CMyClass * B = new CMyClass (); CMyClass & b1 = * B; // This method is not commonly used.

 

 

10) Sun claims that java has eliminated all evil pointers in C ++, and its own object variables are references. Make a comparison:

The C ++ reference cannot be null or new XXX (). The C ++ pointer can be null or new XXX ().

C ++ references objects in the stack, while C ++ pointer new objects are in heap.

 

The object variable in java/C #, which can be null or new XXX (). The object variables in java/C # Are in heap.

 

Therefore, object variables in java/C # are more like pointers in C ++ than references in C ++.

 

11) in C ++, the pointer variable is a long integer and can be out of the box:

CMyClass *obj = (CMyClass *) 99;        //compile/run good, should not use    

If I know a memory address, I can define a C ++ pointer variable pointing to this memory address. C ++'s "reference" does not have this function. C #/Java object variables do not have this function.

Pointer disorder refers to a powerful and flexible expression of the C ++ pointer function (when a video was first played on a PC, it was probably in the intel 486 CPU era, C ++ software usually writes video memory directly, which is said to be faster), which is also the most prone to problems. This is probably because of this reason. Therefore, C #/Java removes this function. The so-called "all-evil C ++ Pointer" usually refers to the "random pointer ".

 

12) C ++ has a wild pointer, that is, the object has been deleted, but the pointer still points to the deleted object. You can continue the operation, but the running result is not guaranteed to be correct.

CMyClass * p = new CMyClass ();... // assign the delete p value to the memory pointed to by p; // at this time, p still points to the previous memory address, which is the data of the memory address. Generally, within a short time, it is not cleared or overwritten, and can still be read/written. This is the "wild pointer ". P-> run (); // The running result may be correct, incorrect, and not guaranteed. // At this time, the memory corresponding to the pointer p may be used by the next new XXX () code. Therefore, theoretically, the pointer after the delete operation should no longer be used to operate the object. P = NULL; // point the pointer to "NULL" to avoid the "wild Pointer" problem. P-> run (); // a running error is reported here. That is, the NULL pointer is abnormal. Null Pointer exceptions are found in java/c.

In C ++, delete should be put together with null values of variables. It can be considered as a "database transaction", which is either successful or failed. In fact, the delete keyword is defined by the C ++ standard. In the standard, the code of the row where the delete statement is located is completely required. After execution, convert pointer variables to null (many of the C ++ standards specify what the compiler is doing, so this provision can be added ). This avoids the problem of wild pointers. Unfortunately, C ++ standards are not fully considered in this regard.

 

In addition, some people complain that the interview is not for C ++, Java, and C #. I hope this article will help me one or two.

---------------------------------------

Welcome to download the trial of the Single Sign-on system, http://zheguisoft.com

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.