Is the size of T& the same as the size of T*?

Viewed 89

In C++, applying the sizeof operator to a reference type returns the size of the referenced type.

So, I wrote this wrapper class to get the size of the reference type itself:

template <typename T>
struct Ref {
    T& ref;
};

and I got that sizeof(Ref<int>) == sizeof(int*); i.e. 4 bytes on a 32-bit architecture, and 8 bytes on a 64-bit architecture.

My questions are:

  1. Is my assumption that sizeof(Ref<T>) is the actual size of T& correct?
  2. If so, am I guaranteed that the size of Ref<T> (hence of T&) is the same as the size of T* for all types T?
1 Answers

The C++ standard actually does not specify this. Typically, references are implemented as pointers under the hood, so it is very likely that they have the same size. But again, as far as C++ standard doesn't specify this, we cannot be sure.

Related