class TempTest{ public: int _uid; }; bool getTestData(std::map& vec,short id,TempTest &data){ auto it = vec.find(id); if (it != vec.end()) { data = it->second; return true; } return false; } int main(){ std::map testMap; // create data TempTest testTemp; testTemp._uid = 1054; testMap[1] = testTemp; TempTest tempData1; // 获取出其引用 getTestData(testMap, 1, tempData1); // 改变其值 tempData1._uid = 9918; // 这样是可以修改成功 可是 感觉 太沉余代码了 想封装成函数... //auto it = testMap.find(1); //if (it != testMap.end()) { // it->second._uid = 9918; //} for (auto &itor:testMap) { std::cout<
Thank you for your help.
You have a wrong understanding of references
getTestData(testMap, 1, tempData1);
This statement does not make tempData1 become a reference to testMap[1]. This function just makes all operations on data in the function reflect the same to tempDada1, so data becomes a reference to tempData1. And your tempdata1 does not reference any elements in testMap at all, so changing tempdata1 will have no effect.
In the getTestData function, your assignment statement data=it-
The solution is to override the copy constructor so that it returns the original object. There is also a way to use pointers.
Change getTestData to setTestData and use data to assign value to it->second