C++: Inheriting from std::map

后端 未结 4 1826
无人及你
无人及你 2020-12-31 00:44

I want to inherit from std::map, but as far as I know std::map hasn\'t any virtual destructor.

Is it therefore possible to call std

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-31 01:04

    The destructor does get called, even if it's not virtual, but that's not the issue.

    You get undefined behavior if you attempt to delete an object of your type through a pointer to a std::map.

    Use composition instead of inheritance, std containers are not meant to be inherited, and you shouldn't.

    I'm assuming you want to extend the functionality of std::map (say you want to find the minimum value), in which case you have two far better, and legal, options:

    1) As suggested, you can use composition instead:

    template
    class MyMap
    {
        std::map m;
        //wrapper methods
        V getMin();
    };
    

    2) Free functions:

    namespace MapFunctionality
    {
        template
        V getMin(const std::map m);
    }
    

提交回复
热议问题