faressoft
faressoft

Reputation: 19651

Does the reference consider as pointer in c++

Does the reference consider as pointer in c++ ?

int &x = y;

Does x have an space in the memory ?

Upvotes: 1

Views: 300

Answers (3)

justin
justin

Reputation: 104698

It's quite common for a reference to be implemented as a pointer under the hood. The Itanium C++ ABI specifies pointers for parameters:

3.1.2 Reference Parameters

Reference parameters are handled by passing a pointer to the actual parameter.

Yes, a reference uses some memory. If its implementation is effectively a pointer, then it would be pointer sized. How a reference is implemented is implementation-defined.

Edit

As Jesse Good cited from the standard, whether a reference requires storage or not is unspecified.

Upvotes: 2

Crashworks
Crashworks

Reputation: 41384

Implementation-dependent and not specified by the standard. The compiler may treat int &x as if it were a pointer, and make space for it on the stack; it may hang onto it in a CPU register (and thus not need stack space); it may realize that it's a different name for an existing object and just conflate the two at runtime.

Here's a couple of situations as an example of how the compiler might do different things with a reference depending on how it's used.

In a function like:

int foo( int x ) 
{
   int &y = x;
   y += 2;
   return y + x;
}

A compiler like MSVC will simply consider y as an alias for x — a different name for the same variable — and quietly replace all mentions of y with x during compilation. Thus the function will actually be compiled as if it were

int foo( int x ) 
{
   x += 2;
   return x + x;
}

But, if you use a reference as a parameter

int foo( int &x )
{
   x += 2; 
   return x;
}

Then x is internally implemented as a pointer and passed into the function on the stack like any other parameter. The compiler treats it as if it were:

int foo( int *x )
{
   (*x) += 2; 
   return *x;
}

The point is that the answer to your question depends on not just which compiler you are using, but also the particular code you're writing. It's not specified by the standard in any way.

Upvotes: 5

Wyzard
Wyzard

Reputation: 34563

Passing a reference as a function argument probably works by passing a pointer. Declaring a reference to an existing variable in the same scope, like in your example, probably just makes both names refer to the same place in memory. But this is implementation-dependent; different compilers may do it differently.

Upvotes: 1

Related Questions