STL容器是否设计为允许继承? [英] Are STL containers designed to allow inheritance?

查看:436
本文介绍了STL容器是否设计为允许继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

是否可以从STL容器继承实现,而不是委托?

我的问题与为什么STL容器没有虚拟析构函数?有些人(包括前一个问题的作者)确信没有虚拟dtor意味着类不可继承。我对这样一个强烈的声明持怀疑态度,所以我要求提供来源或一些推理,但大多数受访者保持沉默。也没有人回复我的答案

My question is related to Why don't STL containers have virtual destructors? Some people (including author of the former question) are convinced that not having virtual dtor implies that class is not inheritable. I am skeptical about such a strong statement, so I asked for the source or some reasoning but most respondents remain silent. Also nobody responded to my answer

所以我认为它是好主意质疑前一个问题中的假设并澄清这一重要问题。 STL容器是否设计为允许继承?更一般地说:继承需要虚拟析构函数吗?

So I think it is good idea to question the assumptions made in the former question and clarify this important issue. Are STL containers designed to allow inheritance or not? And more generally: is virtual destructor required for inheritance?

推荐答案


是否设计了STL容器是否允许继承?

标准库容器允许继承。没有什么能阻止您继承标准库容器类。如果你这样做,你将不会得到任何编译错误。

但它们不是设计用于允许通过Base类指针销毁派生类对象。因此,如果您希望在这种情况下使用继承(简称为动态多态),那么标准库容器显然不是为它而设计的。

Standard library containers allow Inheritance. Nothing stops you from inheriting from a standard library container class. You will not get any compilation errors if you do so.
But what they are not designed for is to allow is destruction of your derived class object through Base class pointer. So if you want to use inheritance for such a scenario(in short for dynamic polymorphism) then standard library containers are clearly not designed for it.


继承需要虚拟析构函数吗?

如果要在指向派生类对象的基类指针上调用 delete ,则基类析构函数只需要是虚拟的。如果基类析构函数不是虚拟的,它将导致未定义的行为。

Base class destructor is only required to be virtual if you intend to call delete on base class pointer pointed to a derived class object. It will result in Undefined behavior if base class destructor is not virtual.

总而言之,规则是:


如果您需要继承动态多态,标准库容器类不是为它而设计的,但如果您不需要它,您可以安全地继承它们。

If you need inheritance for dynamic polymorphism standard library container classes are not designed for it, but If you don't need that you can safely inherit from them.

注意:您在提供的答案链接中的分析是正确的。它只是没有得到回应,可能是因为答案是在原始Q发布后很长时间(几年)发布的。你现在有我的+1。

Note: Your analysis in the answer link you provided is correct. It just didn't get responses probably because the answer was posted long(a few years) after the original Q was posted. You have my +1 there now.

这篇关于STL容器是否设计为允许继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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