C++ 如何销毁命名空间对象
c++ how to destroy namespaced object
我有一个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;
析构函数并不意味着显式调用(尽管您可以这样做)。
相关文章:
- 命名空间中具有.h和.cpp文件的类
- 命名空间:不能在没有对象的情况下调用成员函数
- 命名空间、标头和对象的层次结构
- 由于命名空间而导致的对象实例化错误
- C++将类添加到命名空间以创建新的类对象
- 其他命名空间中的对象没有包含,否则文件相同
- 模板对象的模板友元函数和命名空间
- 不确定如何使用我的类和命名空间创建对象?c++
- 命名空间是否可以用作C++中的对象模板
- C++:如何让函数接受来自任何命名空间的具有相同类名的对象
- C++访问具有相同名称的变量/对象的命名空间中的全局变量/对象
- 在命名空间中,如何定义从内部类返回对象的函数
- OpenGL 不会为不在命名空间中的对象绘制多边形
- 从命名空间返回对象是否安全
- 在指定命名空间后通过指针内联声明对象
- 为什么我们在Qt中处理表单时要为ui对象声明一个命名空间?
- 如何在 c++ 中创建在命名空间内定义的类对象
- 命名空间中的'Foo' 'bar' 不命名头文件中对象成员的类型
- 正在初始化命名空间中的常量对象
- C++ 如何销毁命名空间对象