In my project I have a system of events. You can connect callback to event and everytime somewhere in the code this event is sent your callback(s) are called.
Upon connecting to event you get a token. As long as it is not destroyed the connection is active:
class A
{
A()
{
event_connection = get_dispatcher().connect(event, std::bind(member_function, this));
}
void member_function()
{
dummy_instance++; //any action that uses this field
}
// changed from shared to unique to avoid confusion
//std::shared_ptr<event_connection_token> event_connection;
std::unique_ptr<event_connection_token> event_connection;
dummy_type dummy_instance;
}
Now the problematic scenario: 1. Deconstruction of object of class A starts. 2. Field dummy_instance is destroyed 3. Now event occures 4. Callback is called because event_connection wasnt destroyed yet. 5. Callback tries to access deallocated memory and program crashes.
Therefor I need my event_connection_token always destroyed before any class members that callback is using. Now if I want 100 other programmers to use this event-callback system it would be unprofessional to expect them to always deallocate event_connection_token first in all classes they ever make. We finally come to the question
Q: How can I enforce that every client removes event_connection_token before anything else in client class gets destroyed?
Im looking for either: ...a clever design that will always make sure token is removed first without programmers even thinking about it. or ... a compile time / run-time check that will let programmer know that he needs to modify code so that token is removed first.
EDIT. The "duplicated question" does not address my problem. I know the order of destruction of objects, or even explicitly calling .reset() in destructor will fix my problem. That is however not the solution to my problem. The problem is I don't want to rely that every developer in the project will remember about this rule (as this event-callback system is to be used in many places in the code).
Thanks for all your help Marcin
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire