3

I get why boost::signal is noncopyable (it's because copying a signal doesn't have a clear meaning), but I need a version of it that does provide some sort of copy ctor (either a no-op or one that copies all connections).

The reason I need this is because in my project many objects become noncopyable just by virtue of featuring signals, and to treat them with comfortable value semantics (shared_ptrs are not as comfortable) I need to manually provide copy-ctors, violating DRY. Clearly a sort of quasi-copyable signal would be a good workaround for C++'s ugliness here.

First solution that comes to mind is inheriting signal and providing a copy ctor in the derived class, but that's a no-go because signal doesn't have a virtual dtor.

Thoughts?

4

6 回答 6

7

尝试在信号上保持指针(或 shared_ptr )而不是信号。

于 2009-03-05T19:23:19.077 回答
3

我会在 shared_ptr 内部保存信号。这样,您的对象将直接可复制,并且您可以使用值语义。

于 2009-03-05T20:49:05.390 回答
2

不要衍生。这是个坏主意,而且对你没有任何好处——你的派生类也不能复制。无论您想要公开信号的任何部分,以及您想要实现的任何行为,都可以使用您自己的类来完成,并且只需在幕后使用 boost::signal。

namespace Iraimbilanja {

// the copy constructor doesn't copy the signal, so it doesn't copy the connections...
struct EmptyOnCopySignal
{
private:
    boost::shared_ptr<boost::signal> _signal;
};

// the copy constructor references the same signal, so it copies the connections...
struct CopyableSignal
{
private:
    boost::shared_ptr<boost::signal> _signal;
};

} // namespace Iraimbilanja
于 2009-03-05T19:27:51.187 回答
1

Can you not have a proxy object for your signals? The proxy will maintain both a signal and a reference count. Instead of creating copies of signals, talk to the proxy which will in turn increase/decrease the count. Does that work?

You may want to refer to the Decorator pattern as well.

于 2009-03-05T19:11:19.493 回答
1

在 shared_ptr 内部保存信号将(默认情况下)导致信号被所有复制的对象共享。在一个对象中触发信号将导致通知所有副本上连接到信号的每个插槽。这可能不是您想要的行为。

如果您不希望这种情况发生,您可以编写自己的复制构造函数和复制赋值运算符,然后您将能够指定复制对象时想要发生的情况。

于 2012-03-21T18:52:35.137 回答
1

绝对可以使用boost::ref。这是这个类的主要目的。当线程无法复制时,它也用于以前版本的 boost。唯一的缺点是信号可能在类之外进行管理,因此存储在所有复制的类上的引用始终有效。

于 2009-03-05T23:36:50.370 回答