为什么 std::string 没有虚拟析构函数?
当我从事一个涉及用给定语言定义句子的项目时,我惊讶地发现 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是设计使然。我认为设计者是在暗示该类不应该被子类化。
另请看一下: 为什么不应该从 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?
它并不意味着源自。没有一个标准类是。
增强它们的公认方法是通过封装,而不是继承。
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.