Should I copy an std::function or can I always take a reference to it?

后端 未结 5 1300
轮回少年
轮回少年 2020-12-01 02:40

In my C++ application (using Visual Studio 2010), I need to store an std::function, like this:

class MyClass
   {
   public:
      typedef std::function

        
5条回答
  •  有刺的猬
    2020-12-01 03:14

    Can I store the function as a reference since std::function is just a function-pointer and the 'executable code' of the function is guaranteed to stay in memory?

    std::function is very much not just a function pointer. It's a wrapper around an arbitrary callable object, and manages the memory used to store that object. As with any other type, it's safe to store a reference only if you have some other way to guarantee that the referred object is still valid whenever that reference is used.

    Unless you have a good reason for storing a reference, and a way to guarantee that it remains valid, store it by value.

    Passing by const reference to the constructor is safe, and probably more efficient than passing a value. Passing by non-const reference is a bad idea, since it prevents you from passing a temporary, so the user can't directly pass a lambda, the result of bind, or any other callable object except std::function itself.

提交回复
热议问题