Why does sizeof a reference type give you the sizeof the type?

前端 未结 3 1643
深忆病人
深忆病人 2020-12-31 02:48

According to the standard, in [expr.sizeof] (5.3.3.2) we get:

When applied to a reference or a reference type, the result is the size of the reference

3条回答
  •  被撕碎了的回忆
    2020-12-31 03:16

    Argument 1: A reference should be a synonym of your object hence the interface of the reference should be exactly the same as the interface of the object, also all operators should work in the same way on object and on reference (except type operators).

    It will make sense in the following code:

    MyClass a;
    MyClass& b = a;
    char a_buf[sizeof(a)];
    char b_buf[sizeof(b)]; // you want b_buf be the same size as a_buf
    memcpy(&a, a_buf, sizeof(a));
    memcpy(&b, b_buf, sizeof(b)); // you want this line to work like the above line
    

    Argument 2: From C++ standard's point of view references are something under the hood and it even doesn't say if they occupy memory or not, so it cannot say how to get their size.

    How to get reference size: Since by all compilers references are implemented by help of constant pointers and they occupy memory, there is a way to know their size.

    class A_ref
    {A& ref;}
    sizeof(A_ref);
    

提交回复
热议问题