cdoubleplusgood
cdoubleplusgood

Reputation: 1369

boost signals: Expose signal itself or connect / disconnect methods in class interface?

When having signals in a class, is it considered being good practice to expose the signal itself in the class "interface"?

class MyClass
{
public:
    boost::signals2::signal<void()>& SomethingHappened()
    {
        return m_Signal;
    }

private:
    boost::signals2::signal<void()> m_Signal;
};

I've seen people writing "register" (and possibly "unregister") functions instead:

class MyClass2
{
public:
    boost::signals2::connection RegisterHandler(std::function<void()>& handler)
    {
        return m_Signal.connect(handler);
    }

private:
    boost::signals2::signal<void()> m_Signal;
};

I'd prefer the 1st approach because I don't want to limit the users of my class to the functions I offer. However, is there a good reason to prefer the 2nd approach?

Upvotes: 4

Views: 854

Answers (1)

Igor R.
Igor R.

Reputation: 15075

The 2nd variant is not so good: you don't allow the caller to use signal's tracking mechanism.

But if you'd substitute function with your_signal::slot_type (or event better, your_signal::extended_slot_type), it would provide better encapsulation than the 1st variant. In particular, it would prevent callers from misusing (or abusing) m_Signal, like this:

SomethingHappened().disconnect_all();

Upvotes: 2

Related Questions