Overloading operator-> in C++

﹥>﹥吖頭↗ 提交于 2019-12-20 01:14:18

问题


I have a smart pointer class and I want to overload operator->; it's provided for convenience so I can access the members of the class contained inside the smart pointer directly.

I was looking at the way Boost implements this operator in its shared_ptr template. I noticed they added an assert checking if the pointer is indeed non-null before returning it. Currently, my operator returns the pointer without checking if it's null (essentially, a null pointer is undefined behavior in my current implementation). Should I add this assert as well?

(Also, how is this operator called? I couldn't find this on the web.)


回答1:


It's up to you. You could simply document that using it with a null pointer is undefined and do nothing, you could assert, you could throw an exception. There isn't a right answer. Personally, I would probably throw an exception.




回答2:


Should I add this assert as well?

If you're happy without it, then that's fine. Just make sure it's documented: that's the important thing.

(Also, how is this operator called? I couldn't find this on the web.)

It doesn't really have a name. The standard just calls it "the -> operator", also referring to it as "one of the class member access operators" ([expr.const]).

Wikipedia lists it as "member b of object pointed to by a" (where, yes, other operators are given terse identifiers).



来源:https://stackoverflow.com/questions/6297289/overloading-operator-in-c

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