- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我曾与一位程序员讨论过,其要点是foo
中的以下断言可以通过或不通过,具体取决于编译器。
#include <cassert>
const int i = 0 ;
void foo ( const int& i )
{
assert( &::i == &i ) ;
}
int main ( )
{
foo( i ) ;
}
他告诉我,(&i) 表达式可以计算为某个临时对象的地址。因为我有疑问,所以我在这里。如何将对 temp 的引用传递给函数,如果在函数中我可以检查并使用 i 和参数的地址做任何我想做的事情,并且必须保留预期的语义。?例如
#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
}
可能这样的事情会发生在某个地方,但不是这种情况。这就是我的想法,但我无法从标准中获得完整的证据。
我已经发现了什么(感谢 npw):
来自 [ expr.call#5 ]:
Where a parameter is of const reference type a temporary object is introduced if needed ([dcl.type], [lex.literal], [lex.string], [dcl.array], [class.temporary])
前四个引用文献不适用于我的情况,但第五个给出了希望。
所以我的问题是:标准是否提供保证,foo
中的断言将被保留。?
最佳答案
在第一个代码示例中,&::i == &i
条件始终为真。 const int&
类型的引用直接绑定(bind)到 const int
类型的对象。没有创建临时对象。
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 the initializer expression
- is an lvalue (but is not a bit-field), and “ cv1 T1” is reference-compatible with “ cv2 T2,” or
- [...], then the reference is bound to the initializer expression lvalue in the first case [...]
类型与其自身是引用兼容的。
第二个例子类似:当然,用一个对象的地址初始化一个指针并不会创建一个临时对象。它指向对象。
关于c++ - (&const_object) 可以评估为临时地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43129165/
我曾与一位程序员讨论过,其要点是foo中的以下断言可以通过或不通过,具体取决于编译器。 #include const int i = 0 ; void foo ( const int& i ) {
我是一名优秀的程序员,十分优秀!