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

前端 未结 3 1644
深忆病人
深忆病人 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:13

    It's not particularly important to know how much storage a reference requires, only the change in storage requirements caused by adding a reference. And that you can determine:

    struct with
    {
        char c;
        T& ref;
    };
    
    struct without
    {
        char c;
    };
    
    return sizeof (with) - sizeof (without);
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-12-31 03:27

    The choice is somewhat arbitrary, and trying to fully justify either option will lead to circular metaphysical arguments.

    The intent of a reference is to be (an alias for) the object itself; under that reasoning it makes sense for them both to have the same size (and address), and that is what the language specifies.

    The abstraction is leaky - sometimes a reference has its own storage, separate from the object - leading to anomolies like those you point out. But we have pointers for when we need to deal with a "reference" as a separate entity to the object.

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