c++reference

How will be a reference treated in these cases?


I know when a reference is parameter of a function and that function is inlined, then it would be possible for the reference to be the referent itself and not necessarily a pointer to it, but what about when a reference is not a parameter but is local to a function or global, or is output of a function which is inlined:

//global scope

void someFunc(SomeType & ref){//when function is inline, it's possible for ref to be the referent itself
 //function body
}
int num=7;
int & ref=num;//what about ref here?
void someFunc1(){
 int num=6;
 int & ref=num;//what about ref here?
 //rest of function body
}
int & someFunc2(){//what about output reference here when function is inlined, will it be num itself or a pointer ?
 int num=8;
 return num;
}

Solution

  • David Rodríguez - dribeas already pointed out in a comment that the standard gives compilers quite a bit of latitude, when it comes to references. They may or may not take space; they're not proper objects themselves, etc.

    The behavior you describe for function arguments of reference type (eliminated during inlining) is typical for the freedom that compilers have when it comes to references. But it's a freedom, not an obligation for them. It may not always be possible either: when you call SomeFunc( a>5 ? foo : bar); the compiler is unable to replace the reference with "the" referent itself.

    Your other examples are similarly unconstrained. The global and local references can be optimized out, in theory, because there's nothing that would stop it. The last example can be entirely inlined as exit(NasalDemons()); because you're returning a reference to an object that went out of scope.