C++ 如何销毁命名空间对象

c++ how to destroy namespaced object

本文关键字:对象 命名空间 何销毁 C++      更新时间:2023-10-16

我有一个std::stringstream指针:

std::stringstream *stream;

我创建了一个意图:

stream = new std::stringstream();

如何调用字符串流析构函数?以下操作失败:

stream->~stringstream();

错误:在"("标记之前有预期的类名。如果可能的话,我不想使用命名空间 std。提前感谢您的回复。

这与命名空间无关。您只需在指针上调用delete

delete stream;

但是为什么首先需要一个指针呢?如果分配具有自动存储的对象,则在退出声明它的作用域时,该对象将被销毁:

{
  std::stringstream stream;
} // stream is destroyed on exiting scope.

纯语法:

{
  using std::stringstream; // make the using as local as possible
  stream->~stringstream(); // without using, impossible
                           // note: this destroys the stream but 
                           //       doesn't free the memory
}

但是,我想不出任何合理的用途。在这种情况下,我宁愿调用删除,使用unique_ptr,或者更好的是使用自动存储。

显式析构函数调用在分配器中很有用,但它们是模板化的,因此不需要使用。

当您调用 delete 时将调用析构函数。这样:

delete stream;

析构函数并不意味着显式调用(尽管您可以这样做)。