2

I have the following function:

void editItem(http_request message, std::string attributeToChange, std::vector<std::string> path, std::vector<Item>& items)
{
    message.extract_json().then([=](pplx::task<json::value> task) {
        try {
            std::string strId = path[0];
            int id = stoi(strId);

            for (auto &it: items) {
                if (it.id == id) {
                    json::value val = task.get();
                    int newState = val[U(attributeToChange)].as_number().to_int32();
                    it.state = newState;
                    message.reply(status_codes::OK);
                    break;
                }
                message.reply(status_codes::BadRequest);
            }
        }
        catch (std::exception &e) {
            message.reply(status_codes::BadRequest);
        }
    });
}

and in line: it.state = newState; I have error like this: error: assignment of member ‘Item::state’ in read-only object.

This is how Item struct looks like:

struct Item
{
    int id;
    int state; //0,1,2
    std::string title;
    std::string description;
    std::string owner;
    std::string startDate; // string in format DD-MM-YYYY
    std::string endDate; // string in format DD-MM-YYYY
    std::string priority; //low/medium/hihg
};

There is no const inside. I don't know where coulde be a problem.

How can I fix this error?

1 Answers1

1

Apparently, when you capture by value, the copied items are read-only. Work-around, capture by reference (and you'll also avoid an unnecessary copy):

message.extract_json().then([&](pplx::task<json::value>

To be honest, this suprised me. After doing some research:

This feature appears to have been added out of a concern that the user might not realize he got a copy, and in particular that since lambdas are copyable he might be changing a different lambda’s copy.

Taken from here.

mfnx
  • 2,894
  • 1
  • 12
  • 28