【问题标题】:accessing std::shared_ptr<std::map<>> without using "get"不使用“get”访问 std::shared_ptr<std::map<>>
【发布时间】:2020-11-08 18:46:42
【问题描述】:

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

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

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 中删除了 const。请注意,我的重点是访问映射共享指针内部的数据,而不是它的 const 部分。

【问题讨论】:

  • std::map::operator[] 是非常量,因此不能在 const map 对象上调用。如果你想在tmap指向的地图上调用它,从它的类型中去掉const,然后写(*tmap)[1]
  • 或者,考虑tmap-&gt;at(1) - 如果在map 中找不到密钥,at 将抛出异常。
  • 这能回答你的问题吗? C++ const map element access
  • auto someMap = *(tmap.get()); 制作了map副本。为避免这种情况,请改用引用:const auto &amp;someMap = ...。但就像其他人说的那样,operator[] 不适用于const map,所以放弃const

标签: c++ shared-ptr stdmap


【解决方案1】:

shared_ptr支持指针语义,所以不用get,你可以直接用*或者-&gt;来访问。 get 通常在大多数生产代码中被避免,因为它返回原始指针。顺便说一句,您还可以/应该检查 shared_ptr 是否为空,就像检查原始指针一样。

【讨论】:

    【解决方案2】:

    我认为我正在寻找的 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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-06
      • 1970-01-01
      • 2022-08-24
      • 1970-01-01
      • 1970-01-01
      • 2015-07-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多