Handle connection/disconnection of many signals/slots with boost::signals2

后端 未结 2 1194
粉色の甜心
粉色の甜心 2021-01-20 00:13

I\'ve started using boost::signals2 instead of my old signals-code. I\'m having a problem with administering multiple connections though. Here\'s my problem:

I have

相关标签:
2条回答
  • 2021-01-20 00:26

    What about:

    class PeopleBrowser
    {
    public:
        void AddPerson (Person& p)
        {
            name_change_connections[&p] = p.NameChange.connect(...);
        }
        void RemovePerson(Person& p)
        {
             name_change_connections.erase(&p);
        }
    
    private:
        std::map<Person*, boost::signals2::scoped_connection> name_change_connections;
    };
    

    You might also want to take a look at automatic connection management.

    0 讨论(0)
  • 2021-01-20 00:26

    I haven't tried it myself but according to boost documentation

    When Can Disconnections Occur? (Intermediate)

    Signal/slot disconnections occur when any of these conditions occur:

    • The connection is explicitly disconnected via the connection's disconnect method directly, or indirectly via the signal's disconnect method, or scoped_connection's destructor.
    • An object tracked by the slot is destroyed.
    • The signal is destroyed.

    Unless you use a scoped_connection the connection between a signal and slot will remain valid until either of them is destroyed. So as far as I understand you don't need to store connection objects in a vector. Just connect your signal to your slot as you are doing now.

    When your observed object goes out of scope it will delete the connection by itself.

    This is a much simpler design.

    0 讨论(0)
提交回复
热议问题