-
Notifications
You must be signed in to change notification settings - Fork 147
Object life cycle and callbacks
d5 edited this page Feb 5, 2012
·
2 revisions
Final goal is to provide easy-to-use and simplest syntax for callbacks using C++11 lambda expression.
Prototype codes below: not working.
typedef shared_ptr<tcp> tcp_ptr;
cout << "Starting test server..." << endl << endl;
{
tcp_ptr server(new tcp);
server->bind("0.0.0.0", 8080);
server->listen([=](int status)
{
tcp_ptr client(new tcp);
server->accept(client);
client->read_start([=](const char* buf, int len)
{
if(len > 0)
{
cout << string(buf, len) << endl;
}
client->read_stop();
client->close([=](){
server->close([=](){
cout << "Server closed." << endl;
});
});
});
});
}
return loop::run_default();
This approach pass calling object as the first parameter of the callback, and guarantee that the object persists during the callback is executing.
A a;
a.call({
B b;
b.call({
});
});
In the above code, object a will persist during a.call()'s callback function, however, a is not available(already went out of scope) inside the b.call's callback function.
Therefore, not a good idea.
C++11's lambda expression allows capturing outside variables.
- But, outside variables will go out of scope as soon as their directly nesting callbacks end. This limitation applies to both non-pointer variables and pointer variables. Actually, pointer variable itself is not available inside the callback function, though its pointee object is still alive. And, that also means, that pointee object must be deleted explicitly somewhere else.
- Capturing syntax for pointer variables and non-pointer variables must be different.
To persist objects and make objects' lifecycle management easier, we can use std::shared_ptr<>. See above code example.
- The only thing that user must remember is that: the first callback lambda expression that capture an object must capture it by value(=). Otherwise it will go out-of-scope immediately and not available. For instance, if you change '[=]' to '[&]' in line 8, server variable is not usable in the callback.
This should be the last resort.