reinterpret_cast std::function* to and from void*

2019-06-25 00:51发布

问题:

I'm suffering a segfault in a plugin when I call a std::function in it passed from the main executable, via converting it's address to/from void*. I can reproduce the problem in a few self-contained lines:

#include <iostream>
#include <functional>

int main()
{
    using func_t = std::function<const std::string& ()>;

    auto hn_getter = func_t{[]() {
        return "Hello";
    }};

    auto ptr = reinterpret_cast<void*>(&hn_getter);

    auto getter = reinterpret_cast<func_t*>(ptr);
    std::cout << (*getter)() << std::endl;   // Bang!

    return EXIT_SUCCESS;
}

Even though I'm casting to the original type, it's still segfaulting. Can anyone see where I'm going wrong?

回答1:

The cause of your problem has nothing to do with cast, it's because of the function return a const string &. You need:

using func_t = std::function<const std::string ()>;

And as comments suggest, const here is useless, just:

using func_t = std::function<std::string ()>;