检查引用是否指向C++中的特定对象

检查引用是否指向C++中的特定对象

问题描述:

如何检查引用是否指向C++中的特定对象?检查引用是否指向C++中的特定对象

我的意思是这样的:

int x(0); 
int& xR = x; 
if(xR == x) 
{ 
//xR is refering to x 
} 
else 
{ 
//xR is not refering to x 
} 
+2

'if(&xR ==&x)'? –

template <class T> T* addressof (T& ref) noexcept 

该功能,即使在重载参考操作者(操作者&)的存在下返回 ref的地址。

if(std::addressof(xR) == std::addressof(x)) 
{ 
     yadayadayada 
} 

他们将有相同的地址。

if(&xR == &x) 
{ 
//xR is referring to x 
} 
+0

哦!非常感谢,伙计们! – trafalgarLaww

+1

请注意'operator&'可能会被重载(取决于类型)。如果是这种情况,你仍然可以使用'std :: addressof'。 – Corristo