I encountered with some weird problem. I have class which store its values inside map. But in one case I need to expose map to do some external calculation and possible adding of data inside that map.
And I have next problem. I have shared_ptr of that class and expose map through reference, but during processing map wont accept new data.
I wrote some dummy example of that just to be clear. What is happening here? And why?
Why changes made to map won't hold up after function end?
#include <map>
#include <iostream>
#include <memory>
class MapWrap {
public:
  MapWrap() {}
  ~MapWrap(){}
  std::map<int, int>& getMap() { return map; }
private:
  std::map<int, int> map;
};
void goGo(std::shared_ptr<MapWrap> m){
  auto map = m->getMap();
  std::cout << "Func: before: map size: " << map.size() << std::endl;
  for(int i = 0; i < 3; ++i){
    // This should and will add new value to map.
    if(map[i] == 3){
      std::cout << "blah" << std::endl;
    }
  }
  std::cout << "Func: after: map size: " << map.size() << std::endl;
}
int main(){
  auto mapWrap = std::make_shared<MapWrap>();
  for(int i = 0; i < 3; ++i){
     goGo(mapWrap);
  }
  return 0;
}
EDIT: Removed const from getMap() method.
Aucun commentaire:
Enregistrer un commentaire