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?
Primitive types like
int
do not benefit from move semantics, as moves are exactly the same as copies. Your code can be simplified to:Also avoid using
std::endl
unless you want to force the buffer to be flushed as it's inefficient compared to'\n'
.