Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make std::unique<T> compatible with std::unique<const T, CustomDeleterType>

Tags:

c++

c++11

In the code I have 3 std::unique_ptr pointer types defined for a particular object:

typedef std::unique_ptr<MyObject> nonConstPtrDefaultDelete;

typedef std::unique_ptr<MyObject, std::function<void(MyObject *)>>
                                                       nonConstPtrCustomDelete;

typedef std::unique_ptr<const MyObject, std::function<void(const MyObject *)>>
                                                       ConstPtrCustomDelete;

I ran into a use case where I need to a convert nonConstPtrDefaultDelete into ConstPtrCustomDelete and nonConstPtrCustomDelete into ConstPtrCustomDelete. In other words:

nonConstPtrDefaultDelete a;
nonConstPtrCustomDelete b;

ConstPtrCustomDelete c1(a);  // Compiler error Deleter has incompatible type
ConstPtrCustomDelete c2(b);  // Compiler error Deleter has incompatible type

The main problem comes from incompatibility of types signature for the deleting functions. It is possible to fix the nonConstPtrCustomDelete case by changing the definition of nonConstPtrCustomDelete type in the following way:

typedef std::unique_ptr<MyObject, std::function<void(const MyObject *)>>
                                                         nonConstPtrCustomDelete

However, the most frequent case with DefaultDelete is still producing compilation error, despite it is intuitively clear that conversion is possible. It there a way workaround that limitation and hint the compiler that functions are castable from one into another?

Thank you

like image 236
Andrey R Avatar asked Dec 09 '22 01:12

Andrey R


1 Answers

If you are sure that deleter is proper you can convert DefaultDelete to your type:

nonConstPtrDefaultDelete a;
ConstPtrCustomDelete c1( a.release(), your_deleter );

same with const/non const version. But why you need 2 versions (one for const and 1 for not) is not clear.

like image 187
Slava Avatar answered May 21 '23 09:05

Slava