【问题标题】:How to insert elements into shared pointer of std::map?如何将元素插入到 std::map 的共享指针中?
【发布时间】:2020-04-17 20:44:24
【问题描述】:

我可以像这样插入地图:

std::map<int, int> testMap;
testMap.insert(std::make_pair(0, 1));

但是如果我用这样的共享指针包围地图:

std::shared_ptr<std::map<int, int>> testSharedMap;
testSharedMap->insert(std::make_pair(0, 1));

它不起作用。我收到运行时错误。

Exception thrown: read access violation.
_Scary was nullptr. occurred

std::mapstd::shared_ptr包围时,我该如何使用它?

【问题讨论】:

  • 你需要先分配它。它默认为空。
  • “包围”这个术语很奇怪。指针指向事物;它不会“包围”事物。说testSharedMap 包围了一个地图,就相当于说str 在定义了char * str = nullptr; 之后包围了一个字符。不要被命名模板的语法误导。您的 testSharedMap 只是一个指针。一个智能指针,但仍然只是一个指针。

标签: c++ c++11 shared-ptr smart-pointers stdmap


【解决方案1】:

正如 @CruzJean 在 cmets 中提到的,您需要先分配内存,然后再使用 std::shared_ptr::operator-&gt; 取消引用,否则(来自 cppreference.com)。

行为未定义,如果 存储的指针为空l.

例如,您可以这样做:

#include <iostream>
#include <map>
#include <memory>

int main() 
{
    // convenience type(alias)
    using Map = std::map<int, int>;
    std::shared_ptr<Map> testSharedMap = std::make_shared<Map>();

    // now you can access the valid memory
    testSharedMap->insert(std::make_pair(0, 1));
    testSharedMap->emplace(1, 1);  // or using `std::map::emplace`

    // print the element in the Map by dereferencing the pointer
    for (const auto [key, value] : *testSharedMap)
        std::cout << key << " " << value << "\n";

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-10
    • 1970-01-01
    • 1970-01-01
    • 2015-05-05
    • 1970-01-01
    相关资源
    最近更新 更多