What's wrong with passing C++ iterator by reference?

前端 未结 7 477
隐瞒了意图╮
隐瞒了意图╮ 2020-12-24 05:13

I\'ve written a few functions with a prototype like this:

template 
int parse_integer(input_iterator &begin, input_iterato         


        
相关标签:
7条回答
  • 2020-12-24 06:12

    In my opinion, if you want to do this the argument should be a pointer to the iterator you'll be changing. I'm not a big fan of non-const reference arguments because they hide the fact that the passed parameter might change. I know there's a lot of C++ users who disagree with my opinion on this - and that's fine.

    However, in this case it's so common for iterators to be treated as value arguments that I think it's a particularly bad idea to pass iterators by non-const reference and modify the passed iterator. It just goes against the idiomatic way iterators are usually used.

    Since there is a great way to do what you want that doesn't have this problem, I think you should use it:

    template <typename input_iterator>
    int parse_integer(input_iterator* begin, input_iterator end);
    

    Now a caller would have to do:

    int i = parse_integer(&p, end);
    

    And it'll be obvious that the iterator can be changed.

    By the way, I also like litb's suggestion of returning the new iterator and putting the parsed values into a location specified by an output iterator.

    0 讨论(0)
提交回复
热议问题