Reputation: 1899
I am initializing a shared_ptr to map in a separate function called GetData. This map is passed as argument to GetData function. However, in the main, map comes back empty after the call to GetData function.
#include <memory>
#include <map>
void GetData(std::shared_ptr<std::map<int, int>> data);
int main()
{
std::shared_ptr<std::map<int, int>> data2 = std::make_shared<std::map<int, int>>();
GetData(data2);
return 0;
}
void GetData(std::shared_ptr<std::map<int, int>> data)
{
data = std::make_shared<std::map<int, int>>
(std::initializer_list<std::map<int, int>::value_type>{
{ 1, 2 },
{ 5, 6 },
{ 4, 5 }
});
}
What am I doing wrong here?
UPDATE: If I re-write method as follows while parameter still not passed by reference, I do get map populated in the main after call to GetData method.
void GetData(std::shared_ptr<std::map<int, int>> data)
{
data->insert(std::pair<int, int>(1,2));
data->insert(std::pair<int, int>(45, 2));
}
Upvotes: 0
Views: 3220
Reputation: 104514
Pass data
by reference:
void GetData(std::shared_ptr<std::map<int, int>>& data)
Or preferably, so it makes more sense as function that "gets" and returns something, have the value returned
std::shared_ptr<std::map<int, int>> GetData()
{
return std::make_shared<std::map<int, int>>
(std::initializer_list<std::map<int, int>::value_type>{
{ 1, 2 },
{ 5, 6 },
{ 4, 5 }
});
}
Upvotes: 5