As far as I understand the smart pointers, they are there to avoid memory leaks among other things. However there are often objects which also need to be released, but not by
If you are using unique_ptr
or shared_ptr
, you can provide your custom deleter. The deleter for a unique_ptr
is passed as a template parameter, and
Deleter must be FunctionObject or lvalue reference to a FunctionObject or lvalue reference to function, callable with an argument of type
unique_ptr
::pointer
For the shated_ptr
, the deleter should be provided as the constructor parameter.
class Foo
{
};
class Deleter
{
public:
void operator()(Foo *)
{
std::cout << "deleter";
}
};
int main() {
std::unique_ptr ptr(new Foo());
std::shared_ptr ptr1(new Foo(),
[](Foo*){std::cout << "deleter for shared_ptr";}
);
}
You have to be careful not to cause memory leaks, though.