Search code examples
c++unique-ptrcustom-deleter

Can't constuct a std::unique_ptr with a lambda as a custom deleter


I am trying to declare std::unique_ptr with a custom deleter:

using FILE = int;

FILE *f = nullptr;

std::unique_ptr pf(f, [](FILE *f) {});

but without a success. What is wrong?

How to use a lambda as a deleter? Do I really need decltype?

MSVC compiler error (std==C++17):

error C2641: cannot deduce template arguments for 'std::unique_ptr'

Solution

  • As mentioned in the comments, you cannot use CTAD for constructing a std::unique_ptr if you pass a deleter.

    If you need to use a lambda you can store it in a variable and use decltype to infer its type:

    #include <memory>
    
    //...
    
    using FILE = int;
    FILE* f = nullptr;
    auto my_lambda = [](FILE* f) {};
    std::unique_ptr<FILE, decltype(my_lambda)> pf(f, my_lambda);
    

    Live demo - Godbolt


    As @NebularNoise commented, c++20 supports lambdas in unevaluated contexts. If you can use c++20 (you mentioned you currently use c++17) you can make it a bit shorter:

    using FILE = int;
    FILE* f = nullptr;
    std::unique_ptr<FILE, decltype([](FILE* f) {})> pf(f);
    

    Live demo - Godbolt