Rahul Iyer
Rahul Iyer

Reputation: 21025

Why can't I change the member variables of the object returned by an unordered_map?

I have an unordered_map which I use to store some objects. From time to time, I need to update the member variables of some of the objects in the map. But for some reason, the object in the map does not get updated, and I can't figure out why.

I have a struct:

typedef struct {
    unsigned int JobId : 2;
    bool isActive;
}JobEvent;

I have a class:

class Job{
bool isActive;
void receiveEvent(JobEvent jobEvent);
}

void receiveEvent(JobEvent jobEvent){
isActive = jobEvent.isActive;
}

I have another class:

class MyClass {

    std::unordered_map<int,Job> jobMap;
    void receiveJobEvents(const std::vector<JobEvent>jobEvents);
}

void receiveJobEvents(const std::vector<JobEvent>jobEvents){
    int ctr = jobEvents.size();
    for (int i=0; i<ctr; i++){
        JobEvent jobEvent = jobEvents[i];
        Job job = jobMap[jobEvent.jobId]; 
        job.receiveEvent(jobEvent);
        JobEvent jobEvent2 = jobMap[jobEvent.jobId];
    }
}

The problem is, the value of isActive in Job stored in the unordered_map does not change ? When I step through the debugger, I can see that the value of isActive in job, changes. But when I get jobEvent2 from jobMap (at the same index where I got job from), the value is the original value.

Why is the unordered_map returning a copy ? Shouldn't it return a reference ? Why can't I update the value in the unordered_map ? What am I doing wrong ? How do I correct it ?

Upvotes: 2

Views: 745

Answers (1)

R Sahu
R Sahu

Reputation: 206727

In these lines

    Job job = jobMap[jobEvent.jobId]; 
    job.receiveEvent(jobEvent);

You are making a copy of the Job and changing the copy.

Change the first line to:

    Job& job = jobMap[jobEvent.jobId]; 

Upvotes: 4

Related Questions