在这样的代码中使用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();给我参考迭代器,而不是矢量元素。然后它在第二次调用中更改第一个值已更改。在这种情况下我必须如何使用迭代器和引用?
答案 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();
}
请注意,参考符号&
已从功能签名中删除。