vendredi 5 janvier 2018

C++: lambda callback function life time

I have a C++11 class which is able to send and receive messages. Reception of the messages is asynchronous and therefore it is handled by the callback mechanism. In order to enhance code readability I would like to pass the single-purpose callbacks as lambda functions:

class Transceiver {
public:
    void sendData(int data, std::function<void(int)> callback) {
        this->respCallback = callback;
        /* Send data somewhere. */
        /* The response is received by another thread. */
        /* As soon as the response comes, the callback will be executed. */
    }
private:
    std::function<void(int)> respCallback;
}

Transceiver tr;

void foo() {
    tr.sendData(42, [&tr](int resp) {
        std::cout << "Response received: " << resp << std::endl;
        tr.sendData(...);
    });
}

I tried to compile an example similar to that one above and it worked. But will it work always?

Question 1: In my scenario it is perfectly possible that the lambda callback is executed after the function foo() exits. Since the lambda is defined in the scope of the function foo(), I will call it outside its scope. Is this legal?

Question 2: If I use capture section in my lambda function, the compiler-generated functor also contains some private data (captured variables). Where are they stored (stack, heap...) and when are they cleared?

Aucun commentaire:

Enregistrer un commentaire