如何正确 return 在 C++ 中从迭代器引用对象

How correct return reference to object from iterator in c++

我在这样的代码中使用对 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 的值已损坏。我认为 return *mCurrencyList.rbegin();给我参考迭代器,而不是矢量元素。然后它在第二次调用中发生变化,第一个值发生了变化。在这种情况下我必须如何使用迭代器和引用?

最安全的解决方案是 return copy 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();
}

请注意,引用符号 & 已从函数签名中删除。