Search code examples
c++c++11std-functionstdbindc++14

Is there any way to check if an std::function points to a member of a valid object?


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.


Solution

  • Is there any way to check if an std::function points to a member of a valid object?

    std::function does not point to a "member of an object", it encapsulates a Callable. When you bind it with an object, you get another callable object (of unspecified type actually), that can be stored in an std::function

    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?

    No, there is no way. But as noted by ecatmur, since std::bind copies it's argument(s), you are fine in your example.