Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
602 views
in Technique[技术] by (71.8m points)

c++ - Why do references occupy memory when member of a class?

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 that? Like why does the compiler(I know that it is implementation-specific in general) make a reference a pointer when they are part of a class, as opposed to when they are a temporary variable? So in this code:

class A{
public:
  A(int &refval):m_ref(refval){};
private:
  int &m_ref;
}

m_ref will be treated as a constant pointer(i.e. they do occupy memory).

However, in this code:

void func(int &a){
  int &a_ref = a;
}

the compiler just replaces the reference with the actual variable(i.e. they do not occupy memory).

So to simplify a little, my question basically is: What makes it more meaningful to make references into constant pointers when they are data members than when they are temporary variables?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...