Home >Backend Development >C++ >Do C References Actually Consume Memory?
Dissecting the Memory Footprint of C References
Unlike pointers, which hold the memory address of a variable, C references provide a direct alias to another variable. This raises questions about the memory footprint of references.
Understanding the Memory Layout
Consider the example:
int i = 42; int& j = i; int k = 44;
While i and k occupy 4 bytes each on the stack, j seemingly consumes no memory. This is because j is simply an alias for i, sharing the same memory location.
References as Function Arguments
Even when passed as a function argument, a reference doesn't take up space on the calling stack. Instead, the function stack receives the address of the referenced variable itself, allowing for efficient passing of large objects.
Addressing Memory Allocation for References
However, the compiler does reserve space on the stack for references in certain circumstances, such as when defining local references within functions or when creating classes with member references.
Restrictions on References
The C standard prohibits arrays and references of references. Arrays of references are disallowed due to the potential for dangling references (i.e., references pointing to invalid memory). Additionally, references to references would be redundant, as the reference itself already provides the indirection needed.
The above is the detailed content of Do C References Actually Consume Memory?. For more information, please follow other related articles on the PHP Chinese website!