Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

shared-ptr

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.

like image 295
Albert Avatar asked Nov 29 '13 10:11

Albert


1 Answers

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.

like image 74
ForEveR Avatar answered Oct 31 '22 09:10

ForEveR