重载运算符->在C ++中 [英] Overloading operator-> in C++
问题描述
我有一个智能指针类,我想重载operator->
;提供它是为了方便,所以我可以直接访问智能指针中包含的类的成员.
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.
我正在研究Boost在其shared_ptr
模板中实现此运算符的方式.我注意到他们在返回指针之前添加了一个断言检查指针是否确实为非空.当前,我的运算符返回指针而不检查它是否为空(本质上,空指针在我当前的实现中是未定义的行为).我还应该添加这个断言吗?
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.)
推荐答案
由您决定.您可以简单地记录下使用null指针定义它是未定义的,并且什么也不做,可以断言,可以引发异常.没有正确的答案.就个人而言,我可能会抛出一个异常.
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.
这篇关于重载运算符->在C ++中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!