从迭代器返回对象的引用

时间:2012-05-11 10:55:02

标签: c++ reference vector null iterator

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

我尝试了以下内容:

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
}

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

*i是否正确?如何将0或null作为参考返回?

2 个答案:

答案 0 :(得分:24)

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

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

答案 1 :(得分:3)

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

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