Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::unique pointer and custom lambda deleter error

I am trying to use a std::unique_pointer and supply a custom lambda deleter with it, but I am getting syntax error:

cannot convert from 'wmain::<lambda_0f8f736f48c52ca6fa24492e7c0c1ec0>' to 'const std::default_delete<_Ty>'

with the following simple, minimal code:

#include <memory>

class TestClass
{
};

typedef std::unique_ptr<TestClass> TestClassPtr;


int _tmain(int argc, _TCHAR* argv[])
{
    TestClassPtr testPtr(new TestClass(), [](TestClass* w){ delete w;});

    return 0;
}

Is this the wrong way to supply a lambda deleter to a smart pointer?

like image 218
KaiserJohaan Avatar asked Jul 09 '26 04:07

KaiserJohaan


1 Answers

The deleter must be part of the unique_ptr's type.

typedef std::unique_ptr<TestClass, void(*)(TestClass *)> TestClassPtr;

Your code should work after you make this change. Also, I'm assuming you're going to do something other than simply call delete on the pointer within the deleter. If not, there's no need to supply a custom deleter.

like image 58
Praetorian Avatar answered Jul 11 '26 19:07

Praetorian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!