Why do references occupy memory when member of a class?

后端 未结 3 1991
遥遥无期
遥遥无期 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 
    
    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.

提交回复
热议问题