C++ 从迭代器返回对象的引用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10550011/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:12:23  来源:igfitidea点击:

return reference of an object from an iterator

c++referencevectornulliterator

提问by hakuna matata

I want to return a reference of an object from a vector, and the object is in an iterator object. How can I do that?

我想从一个向量返回一个对象的引用,并且该对象在一个迭代器对象中。我怎样才能做到这一点?

I tried the following:

我尝试了以下方法:

Customer& CustomerDB::getCustomerById (const string& id) {
    vector<Customer>::iterator i;
    for (i = customerList.begin(); i != customerList.end() && !(i->getId() == id); ++i);

    if (i != customerList.end())
        return *i; // is this correct?
    else
        return 0; // getting error here, cant return 0 as reference they say
}

In the code, customerList is a vector of customers, and the function getId returns the id of the customer.

代码中customerList是一个客户向量,函数getId返回客户的id。

Is the *icorrect? And how can I return 0 or null as a reference?

*i正确的吗?以及如何返回 0 或 null 作为参考?

回答by reko_t

return *i;is correct, however you can't return 0, or any other such value. Consider throwing an exception if the Customer is not found in the vector.

return *i;是正确的,但是您不能返回 0 或任何其他此类值。如果在向量中找不到 Customer,请考虑抛出异常。

Also be careful when returning references to elements in vector. Inserting new elements in vector can invalidate your reference if vector needs to re-allocate its memory and move the contents.

返回对向量中元素的引用时也要小心。如果 vector 需要重新分配其内存并移动内容,则在 vector 中插入新元素会使您的引用无效。

回答by suszterpatt

There is no such thing as a "null" reference: if your method gets an id that's not in the vector, it will be unable to return any meaningful value. And as @reko_t points out, even a valid reference may become invalid when the vector reallocates its internals.

没有“空”引用这样的东西:如果你的方法得到一个不在向量中的 id,它将无法返回任何有意义的值。正如@reko_t 指出的那样,当向量重新分配其内部结构时,即使是有效的引用也可能变得无效。

You should only use reference return types when you can always return a reference to an existing object that will stay valid for some time. In your case, neither is guaranteed.

仅当您始终可以返回对将保持有效一段时间的现有对象的引用时,才应使用引用返回类型。在您的情况下,两者都不能保证。