sharptooth
sharptooth

Reputation: 170569

Is using "operator &" on a reference a portable C++ construct?

Suppose I have:

void function1( Type* object ); //whatever implementation
void function2( Type& object )
{
    function1( &object );
}

supposing Type doesn't have an overloaded operator &() will this construct - using operator & on a reference - obtain the actual address of the object (variable of Type type) on all decently standard-compliant C++ compilers?

Upvotes: 2

Views: 174

Answers (3)

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 507413

Yes, and the reason is that on the very beginning of evaluating any expression, references are being replaced by the object that's referenced, as defined at 5[expr]/6 in the Standard. That will make it so the &-operator doesn't see any difference:

If an expression initially has the type "reference to T" (8.3.2, 8.5.3), the type is adjusted to "T" prior to any further analysis, the expression designates the object or function denoted by the reference, and the expression is an lvalue.

This makes it so that any operator that operates on an expression "sees through" the reference.

Upvotes: 6

anon
anon

Reputation:

Yes, it takes the address of the object referred to. Once you have an initialised reference, ALL operations on it are performed on the referred to object.

This is actually a fairly frequently used trope:

struct A {
    A( X & x ) : myx( &x ) {}
    X * myx;
};

Upvotes: 4

Richard Pennington
Richard Pennington

Reputation: 19985

Yes, in 15 characters or more.

Upvotes: 2

Related Questions