Why does operator ++ return a non-const value?

后端 未结 3 711
不思量自难忘°
不思量自难忘° 2020-12-30 23:17

I have read Effective C++ 3rd Edition written by Scott Meyers.

Item 3 of the book, \"Use const whenever possible\", says if we want to prevent rvalues f

3条回答
  •  孤城傲影
    2020-12-30 23:41

    EDIT: This is not really answering the question as pointed in the comments. I'll just leave the post here in the case it's useful anyhow...

    I think this is pretty much a matter of syntax unification towards a better usable interface. When providing such member functions without differentiating the name and letting only the overload resolution mechanism determine the correct version you prevent (or at least try to) the programmer from making const related worries.

    I know this might seem contradictory, in particular given your example. But if you think on most of the use cases it makes sense. Take an STL algorithm like std::equal. No matter whether your container is constant or not, you can always code something like bool e = std::equal(c.begin(), c.end(), c2.begin()) without having to think on the right version of begin and end.

    This is the general approach in the STL. Remember of operator[]... Having in the mind that the containers are to be used with the algorithms, this is plausible. Although it's also noticeable that in some cases you might still need to define an iterator with a matching version (iterator or const_iterator).

    Well, this is just what comes up to my mind right now. I'm not sure how convincing it is...

    Side note: The correct way to use constant iterators is through the const_iterator typedef.

提交回复
热议问题