0

I have a question: Is below piece of code valid and whether it is optimum for sequence generator function in C++14?

auto sequenceGen = [](int&& init) {
    int counter = init;
    return [counter=std::move(counter)]() mutable { return ++counter; };
};
auto getSeq1 = sequenceGen(100);
cout << getSeq1()<< endl;
cout << getSeq1()<< endl;

If not how should it be implemented?

P.W
  • 26,289
  • 6
  • 39
  • 76
  • "piece of code". – user202729 Sep 21 '18 at 11:02
  • It's strange, at least. Why would you pass an int by rvalue reference? Reference size is the same as the pointer size, int is either same or smaller, and why moving it (same considerations). – bobah Sep 21 '18 at 11:09
  • `auto const sequenceGen = [](int init){ return [init]()mutable{ return ++init; } };` should do (but not thread safe). – bobah Sep 21 '18 at 11:11

1 Answers1

0

Primitive types like int do not benefit from move semantics, as moves are exactly the same as copies. Your code can be simplified to:

auto sequenceGen = [](int init) {
    return [init]() mutable { return ++init; };
};

auto getSeq1 = sequenceGen(100);
cout << getSeq1() << '\n';
cout << getSeq1() << '\n';

Also avoid using std::endl unless you want to force the buffer to be flushed as it's inefficient compared to '\n'.

Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416
  • Thanks @vittorio-romeo , for int move semantics is not necessary, but it was only a simplification. I will be using this as template function. – Jarod Smith Sep 21 '18 at 11:08
  • Please mark this answer as accepted (and consider upvoting) if you're satisfied with it @JarodSmith – Vittorio Romeo Sep 21 '18 at 11:10