Using std::unique_ptr inside a map as a key

后端 未结 2 1250
一向
一向 2021-01-18 13:05

I am using Visual Studio 2012. I have a map that looks like this:

std::map,std::unique_ptr

        
相关标签:
2条回答
  • 2021-01-18 13:35

    Look at the template definition for std::map:

    template<
        class Key,
        class T,
        class Compare = std::less<Key>,
        class Allocator = std::allocator<std::pair<const Key, T> >
    > class map;
    

    And now lets look at how you try to instantiate it:

    std::map<
        std::string, 
        std::map<
            std::unique_ptr<sf::Sound>, 
            std::unique_ptr<sf::SoundBuffer>
        >
    > 
    listSoundContainer
    

    The problem here is that a std::unique_ptr<sf::Sound> cannot act as a key.

    What you seem trying to do is to make some kind of list of std::pair<std::unique_ptr<sf::Sound>, std::unique_ptr<sf::SoundBuffer>>

    I would suggest using this instead:

    std::map<
        std::string, 
        std::list<
            std::pair<
                std::unique_ptr<sf::Sound>, 
                std::unique_ptr<sf::SoundBuffer>
            >
        >
    > 
    listSoundContainer
    
    0 讨论(0)
  • 2021-01-18 13:38

    Smart pointers should not be used in combination with STL containers.

    The background is that smart pointers do not behave as expected by the STL-containers. For instance, the STL expects source objects of a copy operation to remain unchanged. This is not the case with smart pointers. This can lead to strange effects as you are experiencing...

    EDIT: My answer was not fully correct. Since C++11 it is possible to use smart pointers, e.g. unique_ptr, with STL-containers.

    0 讨论(0)
提交回复
热议问题