在不使用 "get" 的情况下访问 std::shared_ptr<std::map<>>

accessing std::shared_ptr<std::map<>> without using "get"

我认为这是一个标准问题,但我仍然无法找到解决方案。我可能遗漏了一些非常基本的东西。

我只想访问(只读)std::shared_ptr<std::map<int, int>> 中的数据。 我能找到的唯一方法是实际获取共享指针下的对象并将其用作普通对象:

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];

虽然这可行,但如果可能的话,我更愿意将其用作 shared_ptr。

我能够找到这个 SO question 与共享指针的“[]”运算符相关,但我还是不确定如何使用它。 为了完整起见,我还想知道如何修改这些数据。

TIA

编辑:从 shared_ptr 中删除了常量。请注意,我的重点是访问地图共享指针内的数据,而不是它的常量部分。

shared_ptr支持指针语义,所以不用get,你可以直接用*->访问。 get 通常在大多数生产代码中避免使用,因为它 returns 是原始指针。顺便说一下,你 can/should 也像检查原始指针一样检查 shared_ptr 是否为 null。

我认为我正在寻找的 API 是 at() 因为我可以直接在指针上使用这个 API (无论地图是否为 const)

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;
}