Search code examples
c++design-patternsc++14enclose

C++ sequence generator with init value by function enclosure


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?


Solution

  • 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'.