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

时间:2013-01-28 20:58:09

标签: c++ namespaces destructor

我有一个std :: stringstream指针:

std::stringstream *stream;

我创建了一个intance:

stream = new std::stringstream();

如何调用stringstream析构函数?以下失败:

stream->~stringstream();

错误:在'('token 之前的预期类名。如果可能,我不想使用使用命名空间std 。提前感谢你的回复。

3 个答案:

答案 0 :(得分:4)

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

delete stream;

但为什么你首先需要一个指针?如果您使用自动存储分配对象,则在退出声明范围时将销毁该对象:

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

答案 1 :(得分:3)

纯语法:

{
  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
}

然而,我想不出任何明智的用法。在这种情况下,我宁愿调用delete,使用unique_ptr,或者更好的是,使用自动存储。

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

答案 2 :(得分:1)

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

delete stream;

析构函数不应该被明确调用(尽管你可以这样做)。