0x29a
0x29a

Reputation: 773

Update object by reference in map

I have a simple function which accepts list of objects as an argument and calls one of the objects methods to update the property on each object:

void updateList( std::map<std::string, MyCustomObject> *myList )
{
    for each( std::pair< std::string, MyCustomObject > p in *myList )
    {
        std::string currentObjectKey = p.first;
        MyCustomObject    *currentObject     = &p.second;
        currentObject->setName( "NewName" );
    }
}

And here is MyCustomObject class:

void MyCustomObject::setName(std::string newName)
{
    name = newName;
}

std::string MyCustomObject::getName()
{
    name = newName;
}

The problem is that if I do another loop to read the values updated, I get the original values from when I initialized the list, instead of my new "NewName" value. It seems like the 'p' variable in the for each loop is a copy instead of a reference, therefor it's not really updating.

How can I update the value and access the object by reference instead of a copy?

Upvotes: 0

Views: 274

Answers (1)

KostasRim
KostasRim

Reputation: 2053

The line:

for each(std::pair<std::string, MyCustomObject> p : *myList)

has no effect because it copies the elements of the container. Adjust your code to:

for(auto& pair : *myList)
{
    std::string currentObjectKey = p.first;
    MyCustomObject* currentObject = &p.second;
    currentObject->setName("NewName");
}

Final notes, don't pass strings by value(setName for example). If you intent to inspect the string then a plain string const& or a string_view is the best option(cause you don't copy anything). Pass by reference if you want to modify and by value if you can cheap copy (e.g. an int or a float)

Upvotes: 2

Related Questions