Home  >  Q&A  >  body text

C++ can use (reference) to get the value address in the STL container but cannot change its value.

class TempTest{
public:
    int _uid;
};

bool getTestData(std::map<int,TempTest>& 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<int, TempTest> 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<<itor.second._uid<<std::endl;
    }
    // 发现其值并没有得到改变...
    return 0;
}

Thank you for your help.

習慣沉默習慣沉默2736 days ago686

reply all(3)I'll reply

  • 仅有的幸福

    仅有的幸福2017-05-16 13:30:05

    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.

    reply
    0
  • 某草草

    某草草2017-05-16 13:30:05

    In the getTestData function, your assignment statement data=it-<second; will call the copy constructor of the class. Because you didn't write it, the default copy constructor is called. In other words, your assignment does not bind the object on the right side of the equal sign to the object on the left, but a copy occurs. So your changes to teaData1 will not change the original object.

    The solution is to override the copy constructor so that it returns the original object. There is also a way to use pointers.

    reply
    0
  • PHP中文网

    PHP中文网2017-05-16 13:30:05

    Change getTestData to setTestData and use data to assign value to it->second

    reply
    0
  • Cancelreply