0

I think this is a standard question but still I'm unable to find a solution or this. I might be missing something very basic.

All I want to do is to access (read only) the data within a std::shared_ptr<std::map<int, int>>. The only way I could find is to actually get the object beneath the shared pointer and use it as a normal object:

shared_ptr<map<int, int>> tmap = 
       make_shared<const map<int,int>>(initializer_list<std::map<int,int>::value_type>{{1, 1}});
auto someMap = *(tmap.get());
cout << someMap[1];

Though this works I would prefer to use it as a shared_ptr if possible.

I was able to find this SO question related to the "[]" operator for shared pointers but again i am not sure on how to use it. For the sake of completeness I would also like to know how to modify this data as well.

TIA

Edit: removed the const from the shared_ptr. Please note that my focus is on accessing the data inside of the shared pointer of a map and not the const part of it.

psykid
  • 418
  • 5
  • 15
  • 4
    `std::map::operator[]` is non-const, and so cannot be called on a `const map` object. If you want to call it on the map pointed to by `tmap`, drop `const` from its type, then write `(*tmap)[1]` – Igor Tandetnik Nov 08 '20 at 18:48
  • 1
    Alternatively, consider `tmap->at(1)` - [`at`](https://en.cppreference.com/w/cpp/container/map/at) will throw an exception if the key isn't found in the `map`. – Tony Delroy Nov 08 '20 at 18:51
  • Does this answer your question? [C++ const map element access](https://stackoverflow.com/questions/5134614/c-const-map-element-access) – Lukas-T Nov 08 '20 at 19:19
  • 1
    `auto someMap = *(tmap.get());` makes a *copy* of the `map`. To avoid that, use a reference instead: `const auto &someMap = ...`. But like others said, `operator[]` doesn't work on a `const map`, so drop the `const`. – Remy Lebeau Nov 08 '20 at 23:20

2 Answers2

1

shared_ptr supports pointer semantics, so instead of using get, you may just use * or -> to access. get is usually avoided in most production code for the most part as it returns the raw pointer. By the way, you can/should also check if shared_ptr is null like you would check a raw pointer.

darune
  • 10,480
  • 2
  • 24
  • 62
0

I think the API I am looking for is at() as I can use this API directly on the pointer (irrespective of whether the map is const or not)

auto& someMap = *(tmap.get()); // get the reference to the map instead of copy.
try {
    // either use reference to be able to modify the non-const map
    // or use the "at" api to access the element without [] operator.
    cout << someMap[1] << tmap->at(2);
} catch (const std::out_of_range& oor) {
    cout << "Out of Range error: " << oor.what() << endl;
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
psykid
  • 418
  • 5
  • 15