why reference size is always 4 bytes - c++

前端 未结 2 975
忘掉有多难
忘掉有多难 2020-12-03 03:39

On a 32-bit machine I always get the sizeof of a reference 4 bytes even if it\'s a reference to a double, so what does it really store in this 4 bytes.

<
2条回答
  •  独厮守ぢ
    2020-12-03 04:17

    You can't, and it isn't.

    A C++ reference is not a pointer. It is an alias of an object. Sometimes, the compiler chooses to implement this by using a pointer. But often, it implements it by doing nothing at all. By simply generate code which refers directly to the original object.

    In any case, sizeof applied to a reference type does not give you the size of a reference. So it's not really clear what you're doing, making it impossible to explain what is happening.

    Edit

    Now that you've shown some code, we can answer the question:

    You are taking the size of a class containing a reference. As I said above, a reference is not a pointer, but when necessary, the compiler may fall back to using a pointer to represent it. When you create a class containing a reference, the only (sane) way the compiler can implement it is by defining a class which holds the address of an object. On 32-bit systems, addresses are 32 bits, or 4 bytes, wide. So sizeof such a class will (typically) be 4.

提交回复
热议问题