Why doesn’t std::string have a virtual destructor?

可紊 提交于 2019-12-11 01:21:14

问题


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()); }

回答1:


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?




回答2:


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.



来源:https://stackoverflow.com/questions/9135501/why-doesn-t-stdstring-have-a-virtual-destructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!