【发布时间】:2021-02-07 14:49:40
【问题描述】:
例如,使用原始指针:
Object *obPointer = new Object(); //dynamically allocating memory, meaning we have to delete it, ourselves, later
std::unordered_map<std::string, Objects*> objContainer; //container that holds a string key and a pointer to an object type.
objContainer.emplace("A", obPointer); // placing a string and a pointer to an object into the container. simple enough.
现在,如果我们删除该容器,它不会释放我们分配的内存,即“对象”类型。所以我们必须手动删除它,对吧?
delete obPointer;
objContainer.erase("A");
如果我们没有删除 obPointer,擦除容器是不够的 - 我们会发生内存泄漏。 无论如何,当谈到共享指针时,我不知道这是否有效,因为我们不会对它们调用 delete:
std::shared_ptr<Object> obPointer = std::make_shared<Object>(); //shared pointer
std::unordered_map<std::string, std::shared_ptr<Object>> container;
container.emplace("A", obPointer);
container.erase("A");
智能指针自己清理了吗?还是只有在超出范围时才会自行清理?
【问题讨论】:
-
除非你有共享所有权,否则可能要使用
std::unique_ptr。 -
当然它会“自行清理”。首先,这正是智能指针的用途。
标签: c++ pointers smart-pointers