开发者

Is it good practice to return references to iterators? (Does it even make sense)?

开发者 https://www.devze.com 2023-04-04 23:28 出处:网络
I\'m not sure if this is a legit thing to do here - Returning an iterator by reference: vector::iterator& getElement(cons开发者_运维问答t char* name) {...}

I'm not sure if this is a legit thing to do here - Returning an iterator by reference:

  1. vector::iterator& getElement(cons开发者_运维问答t char* name) {...}

note that my vector holds the elements themselves and not pointers.

At the current state, I've left it by value (without &).

Is there a consensus regarding iterators or can I use both ways?


What would be the point? iterator is in-and-of-itself a kind of reference to something inside the vector. Are you looking to give someone an iterator that you might modify internally? That is, the class handing out the reference to an iterator itself increments it -- points it to another thing in the vector -- and the client somehow has its iterator pointing to the right thing cause it called getElement() before? That's the only application of references to iterators I can think of and it definitely smells bad too me.

But more importantly, there's serious issues with exposing and therefore possibly persisting iterators. Iterators become invalid. If you have an iterator to something internal in your interface, and something deletes or adds to the vector, you won't be able to guarantee the client's iterators are still valid. Then the client accesses their invalid iterator and undefined behavior -- ie a CRASH -- happens.


Returning a parameter by reference only makes sense if the iterator is "owned" by another object and you want the caller to modify the owner's iterator. Which 99% of the time is a bad idea. Generally, an iterator should be treated like a pointer, and a pointer is pretty much always returned/passed by value except for oddball cases.

0

精彩评论

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

关注公众号