简体   繁体   中英

Avoiding lambda copies in c++

I need to pass a user defined lambda to MyClass1 through MyClass2. I want to make sure that there is one move and no copies. Is the code below achieving that? Is there a better way to do this (like using implicit move done by compiler)?

Note: I have control over MyClass1 and MyClass2

#include <functional>

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

class MyClass1 {
 public:
   MyClass1(const MyFunction& func): mFunc(std::move(func)) {}

 private:
   MyFunction mFunc;
};

class MyClass2 {
 public:
  MyClass1* getClass1(const MyFunction& func) {
    return new MyClass1(func);
  }
};

int main() {
  MyClass2 cl2;

  const auto& f = [] (int i) { return i; };

  MyClass1* cl1 = cl2.getClass1(f);
}

Since you can change MyClass1 and MyClass2 you can take the function by rvalue reference and then move it along

#include <functional>

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

class MyClass1 {
 public:
   MyClass1(MyFunction&& func): mFunc(std::move(func)) {}

 private:
   MyFunction mFunc;
};

class MyClass2 {
 public:
  MyClass1* getClass1(MyFunction&& func) {
    return new MyClass1(std::move(func));
  }
};

int main() {
  MyClass2 cl2;
  const auto& f = [] (int i) { return i; };

  MyClass1* cl1 = cl2.getClass1(f);
}

Live Example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM