Home > Backend Development > C#.Net Tutorial > The meaning of C++ references and the nature of references

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

php是最好的语言
Release: 2018-08-06 09:22:05
Original
2486 people have browsed it

1. The meaning of reference

References exist as variable alias, so they can replace pointers on some occasions. References are more readable and practical than pointers. Property

// swap函数的实现对比
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;
}
Copy after login
Note:

The reference parameters in the function do not need to be initialized. The initialization is completed when calling

2. Special references

const reference

In C, you can declare a const reference. The specific usage is as follows:

const Type& name = var;
Copy after login

constReference let The variable has a read-only attribute. This read-only attribute is for the current alias. The variable can be modified in other ways.

int a = 4;              // a是一个变量
const int  & b = a;     // b是a的一个引用,但是b具有只读属性
int * p = (int *)&b;    // p = &a
b = 5;     // err, 引用b 被const修饰,b是一个只读变量
a = 6;     // ok
printf("a = %d\n", a);
*p = 5;    // ok
printf("a = %d\n", a);
Copy after login

When a constant is used to initialize a const reference, C compiler The processor will allocate space for the constant value and use the reference name as an alias for this 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;
}
Copy after login
Conclusion:

Using a constant pair constAfter initializing the reference, a read-only variable will be generated

Question: Do references have their own storage space?

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

Verification program:

#include <stdio.h>

struct TRef
{
    char& r;        // 字符类型引用
};

int main(int argc, char *argv[])
{ 
    char c = &#39;c&#39;;
    char & rc = c;
    TRef ref = { c }; // 用C进行初始化, TRef.r 就是 c的别名了
    
    printf("sizeof(char&) = %d\n", sizeof(char&));     // char引用的大小,引用即变量本身,求所对应的变量本身的大小,即sizeof(char) = 1
    printf("sizeof(rc) = %d\n", sizeof(rc));        // rc是一个引用,即sizeof(c) = 1
    
    printf("sizeof(TRef) = %d\n", sizeof(TRef));    // sizeof(TRef) = 4
    printf("sizeof(ref.r) = %d\n", sizeof(ref.r));  // TRef.r是 c的别名,sizeof(c) = 1

    // sizeof(TRef) = 4
    // 指针变量本身也是占4个字节
    // 引用和指针的关系
    
    return 0;
}
Copy after login

3. The nature of reference

The internal implementation of a reference in C is a pointer constant

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

Note:

1. The C compiler uses pointer constants as the internal implementation of references during the compilation process, so the space occupied by references is the same as that of pointers

2 , From the perspective of usage, the reference is just an alias, and C hides the details of the storage space of the reference for the sake of usability.

#include <stdio.h>

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

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

    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占了4个字节,所以ref也是占4个字节
    */
    return 0;
}
Copy after login

Meaning of reference:

References in C are intended to replace pointers in most cases

  • Functionality : Can meet most situations where pointers need to be used

  • Safety: Can avoid memory errors caused by improper pointer operations

  • Operations : Simple and easy to use, yet powerful

But

references can avoid memory errors in most cases, If the function returns a reference to a local variable, there is no way to avoid

#include <stdio.h>

int& demo()
{
    int d = 0;
    
    printf("demo: d = %d\n", d);
    
    return d;    // 实际上是返回了局部变量的地址,局部变量函数结束就销毁了,返回错误
}

int& func()
{
    static int s = 0;
    
    printf("func: s = %d\n", s);
    
    return s;    // 返回静态局部变量的地址,静态局部变量存储在全局区,函数结束生命周期还在,返回成功
}

int main(int argc, char* argv[])
{
    int& rd = demo();    // rd 成为demo里面返回的局部变量d的别名,出现警告,但是通过编译
    int& rs = func();    // rs 成为静态局部变量 s 的别名
    
    printf("\n");
    printf("main: rd = %d\n", rd);    // rd = 13209588,rd代表的是一个不存在的变量,现在是一个野指针
    printf("main: rs = %d\n", rs);    // rs = 0
    printf("\n");
    
    rd = 10;
    rs = 11;        // 通过rs改变了静态局部变量s的值
    
    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;
}
Copy after login

4. Summary

References exist as variable aliases and are intended to replace pointers

constReferences can Make variables have read-only attributes

References are implemented using pointer constants inside the compiler

The ultimate essence of references is pointers

References can avoid memory errors as much as possible

Related articles:

A pitfall of loops and references in PHP, PHP circular references

Usage of double quotes PHP single quotes The difference with double quotes

The above is the detailed content of The meaning of C++ references and the nature of references. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
c c++
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template