return reference of an object from an iterator

你说的曾经没有我的故事 提交于 2020-01-03 06:49:29

问题


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.

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


回答1:


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.

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.




回答2:


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.

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.



来源:https://stackoverflow.com/questions/10550011/return-reference-of-an-object-from-an-iterator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!