ptr->hello(); /* VERSUS */ (*ptr).hello();

杀马特。学长 韩版系。学妹 提交于 2019-11-27 09:40:54

The -> operator is just syntactic sugar because (*ptr).hello() is a PITA to type. In terms of the instructions generated at the ASM level, there's no difference. In fact, in some languages (D comes to mind), the compiler figures everything out based on type. If you do ptr.hello(), it just works, because the compiler knows that ptr is a pointer and doesn't have a hello() property, so you must mean (*ptr).hello().

Others have already answered regarding built-in pointers. With regards to classes, it is possible to overload operator->(), operator&(), and operator*() but not operator.().

Which means that an object may act differently depending on which syntax you call.

The main advantage in terms of readability comes when you have to chain function calls, i.e.:

ptr->getAnotherPtr()->getAThirdPtr()->print()

I'm not even going to bother doing this with the * operator.

The only reason to have the '->' operator is to make it more convenient and save errors like:

*ptr.hello();

Because it is so easy to forget the parenthesis.

They generate the same exact machine code, but for me, ptr->arg() is much easier to read than (*ptr).arg().

These alternate syntax modes are adopted from C, and you might get some additional understanding from A Tutorial on Pointers and Arrays in C, specifically, chapter 5, Pointers and Structure.

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