Why do references occupy memory when member of a class?

后端 未结 3 1974
遥遥无期
遥遥无期 2020-12-21 16:56

I have been told that references, when they are data members of classes, they occupy memory since they will be transformed into constant pointers by the compiler. Why is tha

相关标签:
3条回答
  • 2020-12-21 17:35

    The C++ standard only defines the semantics of a reference, not how they are actually implemented. So all answers to this question are compiler-specific. A (silly, but compliant) compiler might choose to store all references on the hard-disk. It's just that it proved to be the most convenient/efficient to store a reference as a constant pointer for class members, and replace the occurence of the reference with the actual thing where possible.


    As an example for a situation where it is impossible for the compiler to decide at compile time to which object a reference is bound, consider this:

    #include <iostream>
    
    bool func() {
        int i;
        std::cin >> i;
        return i > 5;
    }
    
    int main() {
        int a = 3, b = 4;
        int& r = func() ? a : b;
        std::cout << r;
    }
    

    So in general a program has to store some information about references at runtime, and sometimes, for special cases, it can prove at compile time what a reference is bound to.

    0 讨论(0)
  • 2020-12-21 17:38

    Imagine that a class is just a user defined data type. You need to have something which can lead you to the actual thing that you are referencing. Using the actual value in the second case is more about the compiler and his work to optimize your code. A reference should be an alias to some variable and why should this alias use memory when it could be optimized to be taken directly from the stack.

    0 讨论(0)
  • 2020-12-21 17:41

    The reference (or pointer) has to be stored in memory somewhere, so why not store it along with the rest of the class?

    Even with your example, the parameter a (int &a) is stored in memory (probably on the stack), then a_ref doesn't use any more memory, it's just an alias, but there is memory used by a.

    0 讨论(0)
提交回复
热议问题