简体   繁体   English

从迭代器返回对象的引用

[英]return reference of an object from an iterator

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 *i correct? *i正确的吗? And how can I return 0 or null as a reference? 我怎么能返回0或null作为参考?

return *i; is correct, however you can't return 0, or any other such value. 是正确的,但是你不能返回0或任何其他这样的值。 Consider throwing an exception if the Customer is not found in the vector. 如果在向量中找不到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. 如果向量需要重新分配其内存并移动内容,则在向量中插入新元素可能会使引用无效。

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. 没有“null”引用这样的东西:如果你的方法得到一个不在向量中的id,它将无法返回任何有意义的值。 And as @reko_t points out, even a valid reference may become invalid when the vector reallocates its internals. 正如@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. 在您的情况下,两者都不保证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM