specialise `std::default_delete` for `std::shared_ptr`

只谈情不闲聊 提交于 2019-12-22 05:34:09

问题


I have the idea to do this:

namespace std {
    template<>
    class default_delete<IplImage> {
    public:
        void operator()(IplImage *ptr) const {
            cvReleaseImage(&ptr);
        }
    };
};

typedef std::shared_ptr<IplImage> IplImageObj;

I didn't really found much information whether it is supported that I specialise default_delete and whether shared_ptr also uses default_delete by default.

It works like intended with Clang 5.0.0.

So, is it supported?

What if the STL implementation has a different internal namespace? It wouldn't find my declaration then? But it should error about the declaration then.


回答1:


default_delete should be defined in std namespace and it's ok to specialize entities from std namespace.

namespace std {
template<class T> struct default_delete;
template<class T> struct default_delete<T[]>;

However, your specialization violates some of the requirements of std::default_delete and thus is UB. Quotes about this thing are here (thanks to R. Martinho Fernandes).

However, shared_ptr is not specified to use default_delete.

~shared_ptr();

Effects:

  • If *this is empty or shares ownership with another shared_ptr instance (use_count() > 1), there are no side effects.

  • Otherwise, if *this owns an object p and a deleter d, d(p) is called.

  • Otherwise, *this owns a pointer p, and delete p is called.



来源:https://stackoverflow.com/questions/20283685/specialise-stddefault-delete-for-stdshared-ptr

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!