简体   繁体   English

std :: unordered_map具有共享指针,可自动销毁条目

[英]std::unordered_map with shared pointer for auto destruction of entries

I have an unordered_map<int, custom_object* > and have various shared pointers pointing to every entry in the unordered_map . 我有一个unordered_map<int, custom_object* >并且有各种共享的指针指向unordered_map每个条目。 The idea is so that once all the shared pointers are destructed, the entry will be removed from the unordered_map . 这样的想法是,一旦所有共享指针都被破坏,该条目将从unordered_map删除。 custom_object currently contains the key so that it can remove the respective entry from the unordered_map upon destruction. custom_object当前包含密钥,以便在销毁时可以从unordered_map删除相应的条目。 I'd like to have a more elegant design, perhaps implementing an unordered_map<int, shared_ptr<custom_object>> instead. 我希望有一个更优雅的设计,或者改为实现unordered_map<int, shared_ptr<custom_object>> Any thoughts on this? 有什么想法吗?

You could use a custom deleter for the shared_ptr that deletes the object and also removes it from the map: 您可以为shared_ptr使用自定义删除器,以删除对象并将其从映射中删除:

class custom_object_deleter
{
public:
    custom_object_deleter(unordered_map<int, custom_object*>* map) :
        map(map)
    {
    }

    void operator()(custom_object* object)
    {
        // Remove object from map.
        delete object;
    }

private:
    unordered_map<int, custom_object*>* map
};

Then when you create a custom_object do this: 然后,当您创建一个custom_object时,请执行以下操作:

shared_ptr<custom_object> my_custom_object(new custom_object, custom_object_deleter(&map));

Sorry I just whipped this up quickly and haven't tested it for compile errors... 抱歉,我只是迅速地将其提示,还没有对其进行编译错误测试...

BUT, this is still not a very elegant solution. 但是,这仍然不是一个很好的解决方案。 You may want to take a step back and check whether the design that requires this is really the best (and simplest!) one. 您可能需要退后一步,检查需要这样做的设计是否真的是最好的(也是最简单的!)设计。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM