删除unique_ptr所指向的对象

Deleting what unique_ptr points to

本文关键字:对象 unique ptr 删除      更新时间:2023-10-16

我有一个编码分配,我需要释放我分配的任何内存,所以我试图删除我的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();

错误很明显:

deletepointer为参数,不以unique_ptr为什么你试图删除一个指针,当你使用unique_ptr为相同的目的?像unique_prtshared_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将具有相同的效果。