c++/java/c# pointers and reference comparisons for several programming languages

Source: Internet
Author: User
Tags java reference

Some time ago, I was in cnblogs someone else's blog, talking about:

References/pointers in Java are not a concept with reference/pointers in c++/c#.

Java reference, equivalent to C + + pointers (FUN3). A Java reference can be assigned a value of NULL, and a C + + reference (see FUN2) cannot be assigned a value null,c++ the pointer can be assigned a value of NULL (FUN3).
In Java, there is no syntax for C + + references (fun2).

The result is unnecessary questioning, hereby, write a blog, to c++/java/c# several programming language pointers, references, compare, expect to cause more people, this is concerned.

Syntactically, in the three development languages, C + + pointers, references, the most complex, so, the following examples, starting from the C + + code, and then compared with the java/c# syntax.

1) C + + Simple type variable, with direct variable definition, pointer definition, reference definition.

    //c++    int &bb = aa;  int *CC = &aa; //c++    

The above three lines of code, the last three variables point to the same data. In comparison, java/c# has only variable definitions, no reference definitions, and pointer definitions. add: Thanks to Xiaotie, flying waves Reminder: C # is a pointer, in the unsafe state, you can define and use pointers. Special corrections.

2) C + + function call parameter, simple type variable, have direct variable definition, pointer definition, reference definition, after two, change data inside function, Exit function, can see the changed data.

void Simple_by_val (int A,ConstIntb) {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,Constint &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< Span style= "color: #000000;" >; //*b = 33; //error c2166:l-value specifies const Object a = NULL; //ok B = NULL; //ok}         

Java does not have so many tricks, only the direct variable definition. C # is slightly more complex, has references, and has out parameters.

        void M (int;}  

In contrast, C # 's function parameters ( ref int B), similar to C + + 's function arguments ( int &a), are to assign the initial value before calling the function, change the data inside the function, exit the function, and see the changed data.

In C # (out int C), there is no corresponding syntax in C++/java. This can be called before the function, without assigning an initial value. Before C #, this syntax was rarely seen, except in some database stored procedures, function definitions, and similar syntax. Estimation is the syntax copied from the database programming syntax.

Special Note : C # references ( ref int b) are used only on function parameter variable definitions and cannot be used in local variables inside the function. A reference in C + + ( int &a), which can be used within a local variable inside a function.

3) C + + class object variable definition syntax, more complex, can be defined on the stack (without new), can be defined in the heap (with new).

    CMyClass obj;                        //stack    new CMyClass ();        //heap    

Java/c#, not so complex, can be considered as the above two "synthesis + simplification".

4) in java/c#, the following usage is wrong and will report null pointer exceptions, but it is legal in C + +.

    CMyClass obj;    Obj.run ();

In C + +,

CMyClass obj;

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

CMyClass obj = null;

5) in C + +, stack variables are scoped, memory is automatically recycled, and heap variables need to be manually delete.

In java/c#, a variable is automatically reclaimed when idle (theoretically), not a variable out of scope, and memory is recycled.

{    CMyClass obj;                        //stack    obj.test ();}  here, the stack variable is automatically deleted, the memory is automatically reclaimed //heap p2->/// here, beyond the scope of the variable P2, the P2 variable can no longer be used, but the memory is not released, There is a memory leak. 

6) The following code is correct in C + + and is wrong in java/c#. In the java/c# syntax, there is no definition of the variable plus *, and you cannot call the class's function or class's member variable, or delete.

Nullnew CMyClass ();p 2->null;  

7) The following code, which is correct in the java/c# syntax, is wrong in C + +. In C + +, this assignment is to be used with a pointer (CMyClass *P1 = null;).

Nullnew CMyClass ();

8) The following code, in C + + code, calls the "copy constructor", "equals sign overloaded function". These two functions, in C + +, are automatically generated by the compiler by default.

    C++
CMyClass obj; // Call constructor cmyclass obj2 = obj; // Call copy constructor obj2 = obj; // call = operator overload function

The above code is roughly equivalent to the clone "clone" in java/c#. But more subtle (beginners do not know that a C + + constructor, copy constructor, = operator overload function) is more complex. java/c# operator-free overloaded functions.

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

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

In C + +, the default is for the compiler to automatically generate "copy constructors", "equals sign overloaded Functions", which can cause problems in many cases and pay special attention.

In C + +, the function return value does not use CMyClass, which causes unnecessary calls to the "copy constructor", "equals sign overloaded function", and does not return a reference cmyclass& a reference to a local variable within a function that cannot continue to be used after exiting the function. Instead, return the pointer CMyClass * (preferably a pointer variable wrapped with a smart pointer). This is a point many beginners don't understand.

Except for C + + std:string. Std:string "copy constructor", "equals sign overloaded function" is optimized, the copied variable, and the copy before the variable, the internal use of the same char[] array, only when a string variable is changed, the char[] array will be copied into two copies. Std:string "Copy Constructors" have no performance loss, and less memory leaks than string pointers, so for std:string, use object variables, object references, object copy constructs whenever possible, and avoid using std:string pointers.

In addition, the string variable of java/c# cannot be changed (there are other classes, such as the Java StringBuilder class is mutable), and the C + + string variable can be changed. This slight difference, many people do not understand.

9) C + + reference syntax, some are java/c# programmers do not know the syntax:

//c++cmyclass &a1; // error, the C + + reference variable is initialized when it is defined; java/c# object variable, initialize cmyclass &a1 = NULL; // error, C + + reference variable cannot be assigned value Nullnew CMyClass (); // error, C + + reference variable cannot be assigned to a new object, in this case, use C + + pointers. // A; CMyClass *b =new CMyClass (); CMyClass &b1 = *b; This is not commonly used.  

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

C + + references cannot be assigned a value of NULL, cannot be assigned a new XXX (), C + + pointers can be assigned null, and can be assigned a value of new xxx ().

C + + Reference objects are usually in the stack, while the C + + pointer new object is in the heap.

The object variable in java/c# can be assigned a value of NULL and can be assigned a value of new XXX (). The object variable in the java/c# is in the heap.

Therefore, the object variable in java/c# is more like a pointer in C + + than a reference in C + +.

One) in C + +, the pointer variable is a long integer that can be randomly referred to as:

;        //compile/run Good, should      not use

If I know a memory address, I can define a C + + pointer variable that points to the memory address. The reference for C + + does not have this feature. The C#/java object variable does not have this function.

"Pointer disorderly refers to" is a powerful, flexible embodiment of C + + pointers (PC on the first video playback, probably the Intel 486 CPU era, C + + software is usually directly write memory, it is said to be faster), but also the most prone to problems. It is estimated for this reason, so C#/java has removed this function. The so-called "evil C + + pointer", mostly, also refers to "pointer disorderly finger".

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 results are not guaranteed to be correct.

 CMyClass *p = new CMyClass (); .... // The memory assigned to p delete p; at this point the P still points to the previous memory address, the memory address data, in general, short time, is not emptied or overwritten, still can read/write. This is the "wild pointer". P->run (); // running results may be correct, may be incorrect, and there is no guarantee. // at this point the memory of the pointer p corresponds to the next new XXX () code, which is used in this memory, so theoretically, The pointer after the delete, and should not be used to manipulate the object. p= NULL; // point the pointer to "NULL" to avoid the "wild pointer" problem. p->run (); // This will report a run-time error. This is the null pointer exception. Null pointer exceptions are available in java/c#.  

In C + +, delete and assign a variable null, should be put together, can be considered as a "database transaction", either success or failure. In fact, thedelete keyword, which is defined by the C + + standard, can be completely required: the code of the delete row, after execution, the pointer variable becomes null (c + + standard specification, many of the rules of the compiler do what, so you can add this rule). This avoids the problem of wild pointers. Unfortunately, the C + + standard is not considered comprehensive in this regard.

Another, someone complains, interview to do the problem, see not is C + + or Java, C #, expect to see this article, can help one or two.

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

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

c++/java/c# pointers and reference comparisons for several programming languages

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.