I want to ask a question about custom deleters in C++.
I have been learning OOP and smart pointers to take care of initialising and deleting objects pointed to by pointers on the heap.
#include <iostream>
#include <memory>
class Test {
private:
int data;
public:
Test() : data {0} {std::cout << "\tTest constructor (" << data << ")" << std::endl;}
Test(int data): data{data} {std::cout << "\tTest constructor (" << data << ")" << std::endl;}
int get_data () const {return data;}
~Test() {std::cout << "\tTest destructor (" << data << ")" << std::endl;}
};
void my_deleter (Test *ptr) {
std::cout << "\tUsing my custom function deleter" << std::endl;
delete ptr;
}
int main () {
{
// using a function
std::shared_ptr<Test> ptr1 {new Test {100}, my_deleter};
}
std::cout << "====================" << std::endl;
{
// using a lambda
std::shared_ptr<Test> ptr2 {new Test {1000},
[] (Test *ptr) {
std::cout << "\tUsing my custom lambda deleter" << std::endl;
delete ptr;}
};
return 0;
}
}
If you look at the function my_deleter
it expects an argument of type Test
and a pointer.
However, when the code is executed in the smart pointer initialisation, the pointer itself isn't passed in as an argument.
std::shared_ptr<Test> ptr1 {new Test {100}, my_deleter};
I'm confused here.
Why is there no argument passed in here but the code still outputs what I require?
OUTPUT
Test constructor (100)
Using my custom function deleter
Test destructor (100)
====================
Test constructor (1000)
Using my custom lambda deleter
Test destructor (1000)
My guess was that similar to OOP with the this
pointer being implicit in C++, the smart pointer object is also implicit when the custom deleter is called after it goes out of scope, but I found nothing to support that statement.
Why do I not need to provide an argument for the deleter inside the smart pointer initialisation?