Search code examples
c++c++17shared-ptrstd-function

How to call std::function after move to shared_ptr


I am stuck on how to call a std::function that has been moved into a shared_ptr…

#include <iostream>
#include <functional>

using func_type = std::function<int()>;

int main(int, char*[])
{   
    func_type func = [] () { return 42; };
    std::cout << func() << "\n"; // -> 42
    auto sp_func = std::make_shared<func_type>(std::move(func));
    // how do we now call the function?
}

I'd be grateful for any (smart) pointers in the right direction.


Solution

  • Well, you've just created a (smart) pointer that points to your function. All you have to do to access the object is to dereference that pointer, then you get your function back.

    In this case you should just use (*sp_func)().

    Notes:

    1. Make sure you parenthesize so you dereference the pointer before trying to call the function; the call operator has a higher precedence than the dereference one.
    2. You should never rely on a moved object again. That is, never in your code try to call func() directly after that move. This is undefined behavior. You don't really know the state of a moved object.