0

Consider the following code in C++17:

#include <bits/stdc++.h>
using namespace std;

class MyClass {
public:
    int attribute;
    MyClass(){
        this->attribute = 1;
    }

    void update(int x){
        this->attribute = x;
    }

};

void testing(){
    map<string, MyClass> mapping;
    MyClass one;
    mapping["hh"] = one;
    cout << one.attribute << endl; //1
    one.update(10);
    cout << one.attribute << endl; //10
    cout << mapping["hh"].attribute << endl; //1
}

int main(){
    testing();
    return 0;
}

Suppose I have a map with a default constructable class as values and I want to update the map by accessing value with the key and then modifying the attributes. The class is and must be updated by a method. The key should remain unchanged.

What is the best way of doing this? [] operator does not seem to work in this case.

温泽海
  • 216
  • 3
  • 16

1 Answers1

0

In this code:

MyClass one;
mapping["hh"] = one;

one is a distinct object, and mapping["hh"] will create its own object if it doesn't already exist in the map. You are then assigning one to that second object, which will copy the current attribute value of one into that object.

Thus, one and mapping["hh"] are separate objects, which is why you see two different attribute values being printed.

To do what you want, you can change this:

MyClass one;
mapping["hh"] = one;

To this instead:

MyClass& one = mapping["hh"];

Now, there is only one object present, the one in the map, and one is just a reference to that object. Now, you will see only one attribute value printed.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770