问题
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