返回对迭代器的引用是一个好习惯吗? (这还有道理吗)?
我不确定这是否是合法的事情 - 通过引用返回迭代器:
- vector::iterator& getElement(const char* name) {...}
请注意,我的向量保存元素本身,而不是指针。
在当前状态下,我已经按值保留了它(没有 &)。
关于迭代器是否存在共识,或者我可以同时使用这两种方式吗?
I'm not sure if this is a legit thing to do here - Returning an iterator by reference:
- vector::iterator& getElement(const 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有什么意义呢?迭代器本身就是一种对向量内部某些内容的引用。您是否希望为某人提供一个您可以在内部修改的迭代器?也就是说,分发对迭代器本身的引用的类会递增它——将其指向向量中的另一个事物——并且客户端以某种方式使其迭代器指向正确的事物,因为它之前调用了 getElement() ?这是我能想到的唯一对迭代器引用的应用,而且它对我来说也确实很糟糕。
但更重要的是,暴露迭代器并因此可能持久存在严重问题。迭代器变得无效。如果您有一个指向界面内部某些内容的迭代器,并且某些内容删除或添加到向量中,则您将无法保证客户端的迭代器仍然有效。然后客户端访问它们的无效迭代器并发生未定义的行为——即崩溃。
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.
仅当迭代器由另一个对象“拥有”并且您希望调用者修改所有者的迭代器时,通过引用返回参数才有意义。 99% 的情况下这都是个坏主意。一般来说,迭代器应该像指针一样对待,并且指针几乎总是按值返回/传递,除了奇怪的情况。
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.