为什么 std::string 没有虚拟析构函数?

发布于 2025-01-02 07:22:26 字数 464 浏览 7 评论 0原文

当我从事一个涉及用给定语言定义句子的项目时,我惊讶地发现 std::string 析构函数不是虚拟的。这使得专门化变得更加困难这个类(我必须创建一个包装器)。为什么标准委员会决定让这个类不是虚拟的?

在 /usr/lib64/gcc/x86_64-pc-linux-gnu/4.5.3/include/g++-v4/bits/basic_string.h 中,我们有:

template<typename _CharT, typename _Traits, typename _Alloc>
class basic_string
{
   ...

  /**
   *  @brief  Destroy the string instance.
   */
  ~basic_string()
  { _M_rep()->_M_dispose(this->get_allocator()); }

When I was working on a project that involved defining sentences in a given language, I was surprised to discover that std::string destructor was not virtual. This made it a lot more difficult to specialize this class (I had to create a wrapper). Why did the standard committee decide to have this class not virtual?

in /usr/lib64/gcc/x86_64-pc-linux-gnu/4.5.3/include/g++-v4/bits/basic_string.h, we have:

template<typename _CharT, typename _Traits, typename _Alloc>
class basic_string
{
   ...

  /**
   *  @brief  Destroy the string instance.
   */
  ~basic_string()
  { _M_rep()->_M_dispose(this->get_allocator()); }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

伴梦长久 2025-01-09 07:22:26

这是设计使然。我认为设计者是在暗示该类不应该被子类化。

另请看一下: 为什么不应该从 c++ 派生标准字符串类?

It is by design. I think the designer is hinting that the class should not be sub-classed.

Also look at this: Why should one not derive from c++ std string class?

陈年往事 2025-01-09 07:22:26

它并不意味着源自。没有一个标准类是。

增强它们的公认方法是通过封装,而不是继承。

It's not meant to be derived from. None of the standard classes are.

The approved way to enhance them is by encapsulation, not inheritance.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文