Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 referenced type.

This seems to go along with the fact that references are unspecified [dcl.ref] (8.3.2.4):

It is unspecified whether or not a reference requires storage

But it seems pretty strange to me to have this kind of inconsistency within the language. Regardless of whether or not the reference requires storage, wouldn't it be important to be able to determine how much size the reference uses? Seeing these results just seems wrong:

sizeof(vector<int>) == 24
sizeof(vector<int>*) == 8
sizeof(vector<int>&) == 24
sizeof(reference_wrapper<vector<int>>) == 8

What is the reasoning behind wanting sizeof(T&) == sizeof(T) by definition?

like image 251
Barry Avatar asked Oct 29 '14 13:10

Barry


2 Answers

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.

like image 138
Mike Seymour Avatar answered Sep 28 '22 03:09

Mike Seymour


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);
like image 31
Mihran Hovsepyan Avatar answered Sep 28 '22 03:09

Mihran Hovsepyan