'C++ - adding to same vector gives different results

So I have this:

std::vector<GameObjectsDatabaseContainer*> GetDatabase();
std::vector<GameObjectsDatabaseContainer*> _container;

std::vector<GameObjectsDatabaseContainer*> GameObjectsDatabase::GetDatabase()  {
    return _container;
}

If I do this:

auto * godc = new GameObjectsDatabaseContainer();
_container.push_back(godc);

It works, however If I do this it does not:

auto * godc = new GameObjectsDatabaseContainer();
GetDatabase().push_back(godc);

Why is that? My understanding is that GetDatabase() is returning basically _container and when I try to add data to it via GetDatabase() it is not working. Why ?

c++


Solution 1:[1]

GetDatabase() is returning _container by value, so it is returning a copy of _container. Any changes the caller makes to that copy is not reflected in _container.

You need to return _container by reference instead:

std::vector<GameObjectsDatabaseContainer*>& GameObjectsDatabase::GetDatabase()  {
    return _container;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1