2

Here is a MRE of my code:

#include <memory>

struct Deleter
{
    void operator() (A* a) {}
};

class A
{
    A(int a) {}
};

int main()
{
    std::unique_ptr<A, Deleter> unique = std::make_unique<A, Deleter>(5);
}

I get this error:

error C2664: 'std::unique_ptr<A,std::default_delete<A>> std::make_unique<A,Deleter,0>(Deleter &&)': cannot convert argument 1 from 'int' to 'Deleter &&'

How should I call A constructor with std::make_unique when I use a custom deleter like that?

AathakA
  • 117
  • 7

1 Answers1

3

You cannot use std::make_unique with a custom deleter. You’ll need to use the regular constructor instead:

auto unique = std::unique_ptr<A, Deleter>(new A(5), Deleter());

Of course this will still require you to fix the rest of your code: make the constructor of A public, and declare A before Deleter. And you’d need to replace new A(…) by the proper construction that matches the custom Deleter.

And it’s worth noting that this might leak memory if the Deleter constructor throws, so you need to make sure that it doesn’t do that.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214