开发者

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 an开发者_JAVA技巧d 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;
}


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.


In the first case when the reference is global it will point the global num to the end of source file. The second case when ref is in someFunc1 it will point num to the end of someFunc1. You shouldn't do as in the last case because num will be destroyed in the end of someFunc2 so you will have a segmentation fault if you use it outside.


then reference will be the referent itself and not necessarily a pointer to it

Semantically, a reference is always (a name for) the object itself, and never a pointer to it.

In terms of implementation, there is no guarantee that if the function is inlined, then no pointer will be used. There is no guarantee about the global or the local variables either. Your someFunc2() creates a dangling reference, with undefined behavior.

In all three valid cases (inline, global, local), it's likely that compilers will avoid using extra space to store a pointer, but if you want to make definite statements then you need to pick a compiler and examine its internals. In the case of a global with external linkage, obviously the executable format has to permit it too.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜