开发者

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

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
};开发者_StackOverflow中文版

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

Are there any guidelines which way is better?


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜