删除unique_ptr所指向的对象
Deleting what unique_ptr points to
我有一个编码分配,我需要释放我分配的任何内存,所以我试图删除我的unique_ptr's指向的所有信号量。unique_ptr都在一个映射中。代码片段:
static map<string, unique_ptr<semaphore>> locks;
这里所有的信号量都是用"new"创建的:
89 unique_ptr<semaphore>& up = locks[article.title];
90 if (up == nullptr) {
91 up.reset(new semaphore(6));
92 }
之后,我尝试删除以下代码中的信号量:
160 for (map<string, unique_ptr<semaphore>>::iterator it = locks.begin(); it != locks.end();
161 ++it) {
162 cout << it->first << endl;
163 delete it->second;
164 }
我得到编译错误:
news-aggregator.cc: In function âvoid processAllFeeds(const string&)â:
news-aggregator.cc:163:14: error: type âclass std::unique_ptr<semaphore>â argument given to âdeleteâ, expected pointer
make: *** [news-aggregator.o] Error 1
要删除unique_ptr
指向的是reset
, unique_ptr
,
it->second.reset();
错误很明显:
delete
以pointer
为参数,不以为unique_ptr
。为什么你试图删除一个指针,当你使用unique_ptr
为相同的目的?像unique_prt
或shared_ptr
这样使用智能指针的意义在于,当不再需要(即超出作用域)时,它们会自动删除指向的对象,或者您显式地使用reset
。
std::unique_ptr
的目的是拥有一个内存分配,并在它超出作用域时自动将其delete
。如果你真的需要提前手动释放唯一指针的内存,有很多方法可以做到(reset
等)。
在您的特定情况下,如果您删除容器中的条目,内存将自动释放。
for (auto it = locks.begin(), endit = locks.end(); it != endit; ++it) {
cout << it->first << endl;
delete it;
}
这里删除的是容器的元素,它隐式地调用unique_ptr
的析构函数,而delete
拥有该析构函数的内存。
如果容器的迭代器被delete操作使无效,则不能使用此模式。
如果你有完整的c++ 11支持,你可以使用:
for (auto it : locks) {
std::cout << it.first << 'n';
delete it.second;
}
但更妙的是:
for (auto it : locks)
std::cout << it.first << 'n';
locks.clear();
对clear
的调用将根据每个元素的值自动调用unique_ptr::~unique_ptr
。如果您没有c++ 11,只需将for循环替换为迭代器循环,调用clear
将具有相同的效果。
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- CMake-按正确顺序将项目与C运行时对象文件链接
- 空基优化子对象的地址
- 将对象数组的引用传递给函数
- 你能重载对象变量名本身返回的内容吗
- C++使用整数的压缩数组初始化对象
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 将对象移动到std::shared_ptr
- 代理对象的常量正确性
- 提升 ASIO 无法识别计时器对象
- 将Ref对象作为类成员
- 将包含C样式数组的对象初始化为成员变量(C++)
- 如何返回一个类的两个对象相加的结果
- 为什么 std::unique 不调用 std::sort?
- 使用std::函数映射对象方法
- 是否需要删除包含对象的"pair"?
- 如何在自删除后将对象设置为nullptr
- 在C++11中,将对象的所有权从一个unique_ptr转移到另一个unique _ptr
- 从自定义对象- std:unique的向量中消除重复项会导致崩溃