简体   繁体   中英

How to insert elements into shared pointer of std::map?

I can insert with map like this:

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

But if I surround the map with shared pointer like this:

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

It doesn't work. I get a runtime error.

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

How can I use the std::map when it was surrounded by std::shared_ptr ?

As @CruzJean mentioned in the comments, you need to first allocate memory, before dereferencing it using std::shared_ptr::operator-> , otherwise(from cppreference.com ).

The behaviour is undefined if the stored pointer is nul l.

For instance, you can do as follows:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM