Error: anonymous function String & type of reference can’t bind to const string type of initial value


void CServiceList::GetAllState(string & retStateString)
        m_servicemap.begin(), m_servicemap.end(),
        [retStateString](const pair<string, CService*> & x)
            CService* instance = x.second;
            instance->GetServerState(retStateString);//Error red line under retStateString
            //declaration of GetServerState. void CService::GetServerState(string & retStateString)

Proposed Error: enter image description here

String & type of reference bind to const string type of initial value, the qualifer will be discarded


void test1()
    string aS = "bs";
    string & bS = aS;
    auto func = [bS]() { return bS; };
    cout << func(); //output: bs
    return ;


First code. string & retStateString -> copy capture [ retStateString ] propose error

Experiment code. string & bS -> copy capture [bS] ok



I don’t think you understand what you are doing or what is the issue.

In first, you capture the string by copy. Since the lambda’s operator () is always marked const the captured string cannot be passes by reference. Only by const reference or pass a copy. Were you to capture the string by reference [&retStateString] the call would compile.

In second, you capture string by copy and then you return a copy of it. That’s all there is.