4

I've recently read that reference variables may or may not occupy any storage even when they are non-static member variables of a class:

When an object of some class C is created, each non-static data member of non-reference type is allocated in some part of the object representation of C. Whether reference members occupy any storage is implementation-defined, but their storage duration is the same as that of the object in which they are members. For non-union class types, members with the same member access are always allocated so that the members declared later have higher addresses within a class object. Members with different access control are allocated in unspecified order (the compiler may group them together). Alignment requirements may necessitate padding between members, or after the last member of a class.

(from http://en.cppreference.com/w/cpp/language/data_members#Layout, emphasis mine)

Questions:

  1. Is my understanding of the above quote correct?

  2. If correct, when a non-static member variable of reference type can be omitted in the actual storage, at least in theory? An example I can imagine right now is something like struct A { int x = 0; int& rx = x; };, but I'm not sure is this really the case.

  3. Is there any practical case this really happens? E.g., sizeof(A) is reported as if a non-static reference data member of A does not exist.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
Junekey Jeon
  • 1,496
  • 1
  • 11
  • 18
  • 1
    The standard is careful in saying that a) objects are things that occupy storage, and b) references are not objects. That's why it's non-committal about how and whether references take up storage. In practice, of course a reference member would be implemented as a pointer. Why does it matter though? I can't think of a way a conforming program would be able to tell the difference. – Igor Tandetnik Oct 13 '17 at 13:53
  • 1
    Marking this as a duplicate of a newer question because the newer question has, for some reason, garnered more attention and therefore more answers. Having a question marked as a duplicate is not a statement on the quality of the question itself, and is not meant as an insult. Just a way to keep the relevant information on the site collected together in one place and as easy-to-find as possible. – Cody Gray - on strike Jul 01 '19 at 23:47

0 Answers0