Difference between &(*similarObject) and similarObject? Are they not same?

痞子三分冷 提交于 2019-12-17 16:27:00

问题


Can someone please explain this to me

dynamic_cast<SomeObject *>( &(*similarObject) );

What is the point of doing the address of a dereferenced pointer? Wouldn’t the pointer itself just be the address of it?


回答1:


It may be that the type of similarObject has overloaded operator* and so it returns something whose address you're passing to dynamic_cast.

&(*x) and x may not be always the same thing. For example, think of iterator:

std::map<int, int>::iterator it = v.begin();

Then it and &(*it) are two different thing:

  • The type of it is std::map<int, int>::iterator
  • The type of &(*it) is std::pair<int,int>*

They're not at all same. Similar thing may happen with your code-snippet as well.




回答2:


If similarObject is a smart pointer, this technique is sometimes used to get the reference of a raw pointer, when * has been overloaded.




回答3:


Nobody mentioned yet that similarObject is an lvalue, whereas &*similarObject is an rvalue.



来源:https://stackoverflow.com/questions/6958520/difference-between-similarobject-and-similarobject-are-they-not-same

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!