Boost logo

Boost Users :

From: Ben Hutchings (ben.hutchings_at_[hidden])
Date: 2004-07-26 09:32:05


Oliver Kowalke <oliver.kowalke_at_[hidden]> wrote:
> Hi,
>
> I want to use boost::shared_ptr with boost::signal.
>
> class A
> {
> private:
>         int     _i;
> public:
>         A() : _i( 0) {}
>
>         void operator()( int, std::string & s)
>         { i+= 1; }
>
>         void operator()( std::string & s, int)
>         { i+= 2; }
> };
>
> boost::shared_ptr< A > a( new A() );
> boost::signal< void( int, std::string &) > rsig;
> boost::singal< void( std::string &, int) > lsig;
>
> rsig.connect( a);
> lsig.connect( a);
>
> rsig(0,"called from right side");
> lsig("called from left side",0);
>
> Because a is a smart_ptr this code would not compile because
> operator() is not a member function. If I dereference the smart
> pointer when I connect to signal, changes of a are never know
> by the other signal instance.
> Maybe I can use a proxy class which aggregates the smart pointer
> but maybe there is a better solution?!

As a general rule, functors are expected to be copiable and not
to have mutable state of their own. So how about putting the
shared_ptr inside A instead:

    class A
    {
    private:
     boost::shared_ptr<int> _i;
    public:
     A() : _i(new int(0)) {}
 
        void operator()(int, std::string & s)
     { *_i += 1; }

        void operator()(std::string & s, int)
     { *_i += 2; }
    };

    A a;


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net