search
HomeBackend DevelopmentC#.Net TutorialThe meaning of C++ references and the nature of references

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;
}
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;

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);

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;
}
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));

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;
}

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;
}

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;
}

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!

Statement
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
From Web to Desktop: The Versatility of C# .NETFrom Web to Desktop: The Versatility of C# .NETApr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# .NET and the Future: Adapting to New TechnologiesC# .NET and the Future: Adapting to New TechnologiesApr 14, 2025 am 12:06 AM

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

Is C# .NET Right for You? Evaluating its ApplicabilityIs C# .NET Right for You? Evaluating its ApplicabilityApr 13, 2025 am 12:03 AM

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

C# Code within .NET: Exploring the Programming ProcessC# Code within .NET: Exploring the Programming ProcessApr 12, 2025 am 12:02 AM

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

C# .NET: Exploring Core Concepts and Programming FundamentalsC# .NET: Exploring Core Concepts and Programming FundamentalsApr 10, 2025 am 09:32 AM

C# is a modern, object-oriented programming language developed by Microsoft and as part of the .NET framework. 1.C# supports object-oriented programming (OOP), including encapsulation, inheritance and polymorphism. 2. Asynchronous programming in C# is implemented through async and await keywords to improve application responsiveness. 3. Use LINQ to process data collections concisely. 4. Common errors include null reference exceptions and index out-of-range exceptions. Debugging skills include using a debugger and exception handling. 5. Performance optimization includes using StringBuilder and avoiding unnecessary packing and unboxing.

Testing C# .NET Applications: Unit, Integration, and End-to-End TestingTesting C# .NET Applications: Unit, Integration, and End-to-End TestingApr 09, 2025 am 12:04 AM

Testing strategies for C#.NET applications include unit testing, integration testing, and end-to-end testing. 1. Unit testing ensures that the minimum unit of the code works independently, using the MSTest, NUnit or xUnit framework. 2. Integrated tests verify the functions of multiple units combined, commonly used simulated data and external services. 3. End-to-end testing simulates the user's complete operation process, and Selenium is usually used for automated testing.

Advanced C# .NET Tutorial: Ace Your Next Senior Developer InterviewAdvanced C# .NET Tutorial: Ace Your Next Senior Developer InterviewApr 08, 2025 am 12:06 AM

Interview with C# senior developer requires mastering core knowledge such as asynchronous programming, LINQ, and internal working principles of .NET frameworks. 1. Asynchronous programming simplifies operations through async and await to improve application responsiveness. 2.LINQ operates data in SQL style and pay attention to performance. 3. The CLR of the NET framework manages memory, and garbage collection needs to be used with caution.

C# .NET Interview Questions & Answers: Level Up Your ExpertiseC# .NET Interview Questions & Answers: Level Up Your ExpertiseApr 07, 2025 am 12:01 AM

C#.NET interview questions and answers include basic knowledge, core concepts, and advanced usage. 1) Basic knowledge: C# is an object-oriented language developed by Microsoft and is mainly used in the .NET framework. 2) Core concepts: Delegation and events allow dynamic binding methods, and LINQ provides powerful query functions. 3) Advanced usage: Asynchronous programming improves responsiveness, and expression trees are used for dynamic code construction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version