mercredi 1 juin 2016

C++ lambda capture, getting uninitialized warning

On compiling the below, I am getting uninitialized warning for variable cc.

#include <iostream>
#include <utility>
using namespace std;
auto foo()
{
    int cc = 1; // Initialized here
    auto task1 = [&cc]()
    {
        cc++; // Here
        cout << "task1 " << cc << endl;
    };
    auto task2 = [&cc]()
    {
        cc++; // Here
        cout << "task2 " << cc << endl;
    };
    return make_pair(task1, task2);
}

int main()
{
    auto lampair = foo();

    lampair.first();
    lampair.second();


    return 0;
}

Warning:

λ g++ -Wall -O2 a.cpp -o a.exe
a.cpp: In function 'int main()':
a.cpp:9:7: warning: 'cc' is used uninitialized in this function [-Wuninitialized]
   cc++;
       ^
a.cpp:6:6: note: 'cc' was declared here
  int cc = 1;
      ^~

Though I am getting the output as expected :

λ a.exe
task1 1
task2 2

Using gcc-6.1.0.

Aucun commentaire:

Enregistrer un commentaire