Inheriting classes from std::

后端 未结 4 1561
甜味超标
甜味超标 2020-12-22 05:41

There are many similar questions and I found both pro and against reasons to use this pattern so I am asking this here:

I need to make a JSON implementation in C++ (

4条回答
  •  隐瞒了意图╮
    2020-12-22 06:01

    is there any specific reason why not to do this?

    Yes. What you obtain with this, is UB. The problem arises from the std:: containers not supporting polymorphism. They were not designed to be inherited from (no virtual destructor) and this means you cannot write a correct/safe destructor sequence.

    Instead, your solution probably should look like this:

    namespace XYZ { // <-- cannot have same name as class here
        class JSON { };
        class object : public JSON {
            std::unordered_map values;
        public:
            JSON& operator[]( const std::string& key );
        };
        class vector : public JSON {
            // same here
        };
      ...
    }; 
    

提交回复
热议问题