如何正确地从c ++中的迭代器返回对象的引用

时间:2015-03-19 17:48:59

标签: c++ vector reference iterator visual-c++-2010

在这样的代码中使用std::vector元素的引用时遇到了麻烦:

class CurrencyList {
public:
    Currency &append(wstring name);
private:
    vector<Currency> mCurrencyList;
};
Currency &CurrencyList::append(wstring name){
    vector<Currency>::iterator currency = findByName(name);
    if(currency != mCurrencyList.end()) 
        return *currency;
    mCurrencyList.push_back(Currency(name));
    return *mCurrencyList.rbegin();
}

在此代码中使用:

Currency& BaseVal = currencyList.append("AAA");
Currency& ProfitVal = currencyList.append("BBB");
return new CurrencyPair(name, BaseVal, ProfitVal);

当我在第二行收到ProfitVal时,BaseVal的值被损坏。我认为返回* mCurrencyList.rbegin();给我参考迭代器,而不是矢量元素。然后它在第二次调用中更改第一个值已更改。在这种情况下我必须如何使用迭代器和引用?

1 个答案:

答案 0 :(得分:0)

最安全的解决方案是返回Currency副本

Currency append(const wstring& name)  // Note the return type.
{
    vector<Currency>::iterator currency = findByName(name);
    if(currency != mCurrencyList.end()) 
        return *currency;
    mCurrencyList.push_back(Currency(name));
    return *mCurrencyList.rbegin();
}

请注意,参考符号&已从功能签名中删除。