(& const_object) can be evaluated at the address of the temporary

I had a discussion with one programmer, and his main task was that the next statement in foo can be passed or not, depending on the compiler.

 #include <cassert> const int i = 0 ; void foo ( const int& i ) { assert( &::i == &i ) ; } int main ( ) { foo( i ) ; } 

he told me that the expression (& i) can be evaluated to refer to some temporary object. since I have doubts, I'm here. how can the temp reference be passed to the function, if in the function I can check and do whatever I want with i, and the parameter addresses and expected semantics should be saved.? eg

 #include <initializer_list> const int i = 0 ; bool func ( const int & i ) { return &::i == & i ; } int main () { const int i = 0 ; for ( const int * each : { &::i , &i , } ) if ( func( * each ) ) break ; // etc } 

Probably such a thing could happen somewhere, but not for this case. that’s how I think, but I can’t get the full proof from the standard.

what i already found (thanks npw ):

from [ expr.call # 5 ]:

If the parameter is a const reference type, then the temporary object is (if necessary) ([dcl.type], [lex.literal], [lex.string], [dcl.array], [class.temporary])

the first four links are not applicable to my case, but the fifth gives hope.

so my question is: does the standard give a guarantee, will this statement in foo be fulfilled.?

+5
source share
1 answer

In the first code example, the condition &::i == &i always true. A reference of type const int& bound directly to an object of type const int . No temporary object created.

C ++ 14 [dcl.init.ref] / 5:

A reference to type "cv1 T1" is initialized by an expression of type "cv2 T2" as follows:

  • If the reference is an lvalue reference and an initializer expression
    • is an lvalue (but not a bitfield), and "cv1 T1" refers to "cv2 T2" or
    • [...] then the link is bound to the value of the lvalue initializer in the first case [...]

The type is self-referenced.

The second example is similar: of course, initializing the pointer with the address of the object does not create a temporary one. He points to an object.

+6
source

Source: https://habr.com/ru/post/1266144/


All Articles