Conversion operator vs constructor from given type. Which is preferable?

两盒软妹~` 提交于 2020-01-04 05:25:15

问题


I'm defining iterator types for my container and of course I want iterator to be convertible to const_iterator. But I'm not sure which is better/preferable:

Conversion operator in iterator

class iterator
{
    operator const_iterator();
};

or non-explicit constructor in const_iterator

class iterator
{
    // implementation
    friend class iterator; // hard to avoid this
};

class const_iterator
{
    const_iterator(iterator const &);
};

Are there any guidelines which way is better?


回答1:


You should write a casting operator only if it is possible to return the desired type without constructing a new object, or if its return is a simple data type. For example, if it were to return a const reference to a property within the class, then you should write it as a casting operator.

In all other cases, you should just write the appropriate constructor.




回答2:


As a general rule:

There is almost never a good reason to provide implicit conversion operators; it is always preferable to use conversion constructors. With implicit conversion operators you will seldom find them invoked when you don't expect and create unnecessary confusions.

conversion constructors is also a better way since it lets you adheres you to the Principle of least Astonishment.

The only common exception to this rule is provide a conversion to a boolean type, so that objects (e.g., smart pointers) can be used in boolean contexts.




回答3:


Some implementations let iterator inherit from const_iterator, and get the conversion for free.



来源:https://stackoverflow.com/questions/6095802/conversion-operator-vs-constructor-from-given-type-which-is-preferable

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