The meaning of C + + reference and the nature of reference

Source: Internet
Author: User


1, the meaning of the reference



References exist as variable aliases, so in some cases you can substitute pointers for better readability and usability relative to pointers


// Comparison of the implementation of the swap function
void swap (int & a, int & b)
{
     int t = a;
     a = b;
     b = t;
}

void swap (int * a, int * b)
{
     int t = * a;
     * a = * b;
     * b = t;
}
Note:

The reference parameter in the function does not need to be initialized, and initialization is done at the time of the call.


2. Special references



const reference



You can declare references in C + +, using theconstfollowing:


Const type& name = var;


constThe reference lets the variable have a read-only property, which is a read-only property for the current alias, and the variable can be modified by other means


int a = 4; // a is a variable
const int & b = a; // b is a reference to a, but b has a read-only attribute
int * p = (int *) & b; // p = & a
b = 5; // err, reference b is modified by const, b is a read-only variable
a = 6; // ok
printf ("a =% d \ n", a);
* p = 5; // ok
printf ("a =% d \ n", a);


Whenconsta reference is initialized with a constant, the C + + compiler allocates space for the constant value and uses the reference name as the alias for the space


#include <stdio.h>
void Example()
{
    printf("Example:\n");  
    int a = 4;
    const int& b = a;
    int* p = (int*)&b;  
    //b = 5;    // b  
    *p = 5;   
    printf("a = %d\n", a);
    printf("b = %d\n", b);
}

void Demo()
{
    printf("Demo:\n");  
    const int& c = 1;
    int* p = (int*)&c;   
    //c = 5;
    *p = 5;
    printf("c = %d\n", c);
}

int main(int argc, char *argv[])
{
    Example(); 
    printf("\n");  
    Demo();
    
    return 0;
}
Conclusion:

constA read-only variable is generated after the reference is initialized with a constant


Question: Does the reference have its own storage space?


struct TRef
{
    char& r;
}
printf("sizeof(TRef) = %d\n, sizeof(TRef));


Verification Program:


#include <stdio.h>

struct TRef
{
     char & r; // character type reference
};

int main (int argc, char * argv [])
{
     char c = 'c';
     char & rc = c;
     TRef ref = {c}; // Initialize with C, TRef.r is an alias for c
    
     printf ("sizeof (char &) =% d \ n", sizeof (char &)); // The size of the char reference, the reference is the variable itself, find the size of the corresponding variable itself, that is, sizeof (char) = 1
     printf ("sizeof (rc) =% d \ n", sizeof (rc)); // rc is a reference, ie sizeof (c) = 1
    
     printf ("sizeof (TRef) =% d \ n", sizeof (TRef)); // sizeof (TRef) = 4
     printf ("sizeof (ref.r) =% d \ n", sizeof (ref.r)); // TRef.r is an alias for c, sizeof (c) = 1

     // sizeof (TRef) = 4
     // The pointer variable itself also takes 4 bytes
     // The relationship between references and pointers
    
     return 0;
}


3, the nature of the reference


The
internal implementation of the reference in C + + is a Pointer constant


Attention:

1. The C + + compiler uses pointer constants as the internal implementation of the reference during compilation, so the reference takes up much less space than the pointer

2, from the perspective of use, reference is just an alias, C + + for usability and hide the reference storage space this details.

#include <stdio.h>

struct TRef
{
     char * before; // 4 bytes
     char & ref; // 4 bytes
     char * after; // 4 bytes
};

int main (int argc, char * argv [])
{
     char a = 'a';
     char & b = a;
     char c = 'c';

     TRef r = {& a, b, & c};

     printf ("sizeof (r) =% d \ n", sizeof (r)); // sizeof (r) = 12
     printf ("sizeof (r.before) =% d \ n", sizeof (r.before)); // sizeof (r.before) = 4
     printf ("sizeof (r.after) =% d \ n", sizeof (r.after)); // sizeof (r.after) = 4
     printf ("& r.before =% p \ n", & r.before); // & r.before = 0xbuf8a300c
     printf ("& r.after =% p \ n", & r.after); // & r.after = 0xbuf8a3014

     / *
      0xbuf8a3014-0xbuf8a300c = 8
      before takes 4 bytes, so ref also takes 4 bytes
     * /
     return 0;
}

Meaning of the reference:

References in C + + are designed to replace pointers in most cases

  • Functionality: can meet most need to use the hands of the occasion

  • Security: Avoid memory errors due to improper pointer operation

  • Operability: Easy to use, yet powerful





References can avoid memory errors in most cases, and functions that return references to local variables cannot be avoided.


#include <stdio.h>

int & demo ()
{
    int d = 0;
    
    printf ("demo: d =% d \ n", d);
    
    return d; // In fact, the address of the local variable is returned. The local variable function is destroyed when it ends, and an error is returned.
}

int & func ()
{
    static int s = 0;
    
    printf ("func: s =% d \ n", s);
    
    return s; // return the address of the static local variable, the static local variable is stored in the global area, the function ends the life cycle is still there, return success
}

int main (int argc, char * argv [])
{
    int & rd = demo (); // rd becomes an alias of the local variable d returned in the demo, a warning appears, but it compiles
    int & rs = func (); // rs becomes an alias for the static local variable s
    
    printf ("\ n");
    printf ("main: rd =% d \ n", rd); // rd = 13209588, rd represents a non-existent variable, now a wild pointer
    printf ("main: rs =% d \ n", rs); // rs = 0
    printf ("\ n");
    
    rd = 10;
    rs = 11; // changed the value of the static local variable s through rs
    
    demo (); // d = 10
    func (); // s = 11
    
    printf ("\ n");
    printf ("main: rd =% d \ n", rd); // rd = 13209588
    printf ("main: rs =% d \ n", rs); // rs = 11
    printf ("\ n");
    
    return 0;
} 


4. Summary


reference as a variable alias exists to replace the pointer

ConstReference can make a variable with a read-only property

Reference within the compiler uses pointer constants to implement the final essence of the

Reference as a pointer

References can avoid memory errors as much as possible

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.