user2145184
user2145184

Reputation: 510

Why are my values in a C++ map class member wiped?

I have 2 classes: InuReading and InuTask. Looking like this:

InuReading header:

class InuReading{
    public:
        InuReading(String t, String l){
            type = t;
            label = l;
        };
        String type;
        String label;
        std::map<String, String> data;
        void set(String key, float d);
};

InuTask header:

class InuTask{
    public:
        InuTask(String);
        String type;
        void addTemperatureReading(String sensor, float temperature);
        std::vector<InuReading> readings;
    private:
        InuReading newReading(String t, String l);

};

InuReading method:

void InuReading::set(String key, float d){
    data[key] = String(d); 
};

InuTask methods:

InuTask::InuTask(String t){
    type = t;
}

InuReading InuTask::newReading(String t, String l){
    InuReading r(t, l);
    readings.push_back(r);
    return r;
}

void InuTask::addTemperatureReading(String sensor, float temperature){
    InuReading r = newReading("temperature", sensor);
    r.set("d", temperature);
    // Size here after setting "d" to 30.0 is 1, which is proper
    Serial.printf("Size of %s is now: %i \n", r.type.c_str(), r.data.size());
}

Main:

InuTask task("Log");
task.addTemperatureReading("Temperature", 30);
// This returns 0, all data is missing now?
Serial.println(task.readings[0].data.size());

Immediately after data is set on the map, it has 1 element, but once I get the InuReading from the vector its data property is empty. How do I get the data to stick in the map?

Upvotes: 2

Views: 189

Answers (1)

newReading returns the InuReading by value, which means that r in addTemperatureReading is a local object and has no relationship whatsoever to the objects stored in the task's readings vector.

You probably want newReading to return a reference, and change addTemperatureReading to use a reference too:

void InuTask::addTemperatureReading(String sensor, float temperature){
    InuReading &r = newReading("temperature", sensor);
    r.set("d", temperature);
    // Size here after setting "d" to 30.0 is 1, which is proper
    Serial.printf("Size of %s is now: %i \n", r.type.c_str(), r.data.size());
}

Note that this change also requires you to return a reference into the readings vector from newReading:

InuReading& InuTask::newReading(String t, String l){
    readings.push_back(InuReading(t, l);
    return readings.back();
}

Upvotes: 3

Related Questions