Let me demonstrate what I mean.
#include <functional>
#include <iostream>
class MyClass
{
private:
int number;
public:
MyClass()
{
number = 0;
}
void printNumber()
{
std::cout << "number is " << number << std::endl;
number++;
}
};
int main()
{
std::shared_ptr<MyClass> obj = std::make_shared<MyClass>();
auto function = std::bind(&MyClass::printNumber, obj);
function();
// This deallocates the smart pointer.
obj.reset();
// This shouldn't work, since the object does not exist anymore.
function();
return 0;
}
This outputs:
number is 0
number is 1
If we were to call the function like we would normally, replacing "function()" with "obj->printNumber()", the output is:
number is 0
Segmentation fault: 11
Just like you would expect it to be.
So my question is if there is any way to make sure that we are unable to call the function when the object has been deallocated? This has nothing to do with using smart pointers, it works the same way with regular pointers.