继承类std :: [英] Inheriting classes from std::

查看:243
本文介绍了继承类std ::的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多类似的问题,我发现使用这种模式的赞成和反对的理由,所以我在这里问:



我需要做一个JSON实现C ++(让我们说它有点像家庭作业)。我想这样做:

 命名空间JSON {
class JSON {};
类对象:public JSON,public std :: unordered_map< std :: string,JSON> {};
class vector:public JSON,public std :: vector< JSON> {};
class string:public JSON,public std :: string {};
...
};

如果你考虑它,这一切都有意义。 JSON对象is-anunordered_map,JSON向量is-a向量等。只是它们也是一个JSON值,例如,一个JSON向量可以包含任何类型的JSON值(对象,向量,字符串等)。你也可以得到很多好处,你可以在C ++中自然使用JSON(你可以在json [mystringlist]里面加入一个实际的std :: string向量,json实际上是一个unordered_map)。



我不是一个真正的C ++专家,但有什么特别的原因,为什么不这样做?

解决方案<


是的,有什么特别的原因吗?你得到的是什么,是UB。问题产生于 std :: 容器不支持多态性。它们不是被设计为继承自(没有虚拟析构函数),这意味着你不能写一个正确/安全的析构序列。



相反,你的解决方案应该看起来像这样:

 命名空间XYZ {//<  - 不能与类名相同
class JSON {};
class object:public JSON {
std :: unordered_map< std :: string,JSON>值;
public:
JSON& operator [](const std :: string& key);
};
class vector:public JSON {
// same here
};
...
};


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++ (let's say that it is sort of like a homework). I was thinking to do it like this:

namespace JSON {
  class JSON { };
  class object : public JSON, public std::unordered_map<std::string,JSON> { };
  class vector : public JSON, public std::vector<JSON> { };
  class string : public JSON, public std::string { };
  ...
};

If you think about it, it all make sense. The JSON object "is-an" unordered_map, the JSON vector "is-a" vector and so on. Just that they are also a JSON value and, for example, a JSON vector can contain any type of JSON values (objects, vectors, strings etc.). You get a lot of benefits too, you can then just use the JSON "naturally" in C++ (you can have an actual std::string vector inside json["mystringlist"], json being actually an unordered_map).

I am not really a C++ expert but is there any specific reason why not to do this?

解决方案

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<std::string,JSON> values;
    public:
        JSON& operator[]( const std::string& key );
    };
    class vector : public JSON {
        // same here
    };
  ...
}; 

这篇关于继承类std ::的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆