Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 618
sharptooth Avatar asked Aug 05 '26 04:08

sharptooth


2 Answers

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.

like image 198
Johannes Schaub - litb Avatar answered Aug 06 '26 20:08

Johannes Schaub - litb


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;
};