Can std::function be serialized?

2019-06-17 02:06发布

问题:

This is a theoretical question. Say there are some objects which among others contain lists of callback functions subscribed to events of those objects. Now we want to store those objects on disk. Is a std::function serializable?

回答1:

No.

Whenever using type erasure (ie, hiding implementation details behind an interface), the only operations available without knowing the dynamic type of the object are those provided by the interface.

There is no serialization in the C++ Standard, and there is no easy way to serialize functions either (without reflection), thus the std::function interface does not provide serialization.

On the other hand, nothing prevents you from using a Callback base class that provides serialization support.



回答2:

std::function is a type erasure object that obeys value semantics. It exposes copy/move construction and assignment, and execution of a particular signature, and destruction.

None of these are serialization.

Internally, the typical implementation of std::function is to create a implementation helper template class on its constructed-from argument, which wraps the above operations on the argument, then the std::function itself delegates its implementation of those operations to the helper object.

The layout of that helper object is going to be dependent on the layout of the argument constructed from (on top of its existence being optional, and its implementation being implementation dependent).

You could try to create a similar object that supports serialization, but a type erasure object relies on the fact that the type being erased already implements the operation in question. Which means you can only construct a type erased function-with-serialization from an object that supports function-with-serialization interface at least at the ducktype level.



回答3:

Yes, it is and no, it isn't. In theory, you can serialize data the function object will be run on, but you will need the code compiled anyway, as you cannot execute data without resorting to ugly hacks.