C++ unique_ptr and map

前端 未结 4 1969
抹茶落季
抹茶落季 2020-12-13 19:19

I\'m trying to use the C++0x unique_ptr class inside a map like so:

// compile with `g++ main.cpp -std=gnu++0x`

#include     
#include 

        
4条回答
  •  一向
    一向 (楼主)
    2020-12-13 20:02

    I've just been tinkering with unique_ptr in gcc 4.6.0. Here's some (very ugly) code which works correctly:

    std::map > table;
    table.insert(std::pair>(15, std::unique_ptr(new int(42))));
    table[2] = std::move(table[15]);
    for (auto& i : table)
    {
        if (i.second.get())
            printf("%d\n", *i.second);
        else
        {
            printf("empty\n");
            i.second.reset(new int(12));
        }
    }
    printf("%d\n", *table[15]);
    

    The output is 42, empty, 12 - so apparently it works. As far as I can tell, the only 'problem' is that awful looking insert command. 'emplace' isn't implemented in gcc 4.6.0

提交回复
热议问题