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

后端 未结 5 1314
轮回少年
轮回少年 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条回答
  •  萌比男神i
    2020-12-01 03:04

    Copy as much as you like. It is copyable. Most algorithms in standard library require that functors are.

    However, passing by reference will probably be faster in non-trivial cases, so I'd suggest passing by constant reference and storing by value so you don't have to care about lifecycle management. So:

    class MyClass
    {
    public:
        typedef std::function MyFunction;
        MyClass (const Myfunction &myFunction);
              // ^^^^^ pass by CONSTANT reference.
    private:
        MyFunction m_myFunction;    // Always store by value
    };
    

    By passing by constant or rvalue reference you promise the caller that you will not modify the function while you can still call it. This prevents you from modifying the function by mistake and doing it intentionally should usually be avoided, because it's less readable than using return value.

    Edit: I originally said "CONSTANT or rvalue" above, but Dave's comment made me look it up and indeed rvalue reference does not accept lvalues.

提交回复
热议问题