简体   繁体   English

有没有办法对不可复制的对象使用增强信号和插槽?

[英]Is there a way to use boost signals and slots with non-copyable objects?

I would like to pass a non-copyable object to a boost signal. 我想将不可复制的对象传递给提升信号。 See the code below (doesn't compile). 请参见下面的代码(无法编译)。 Is there a possible workaround? 有没有可能的解决方法?

#include <boost/signals2.hpp>
#include <iostream>
#include <memory>

struct MySlot
{
  void operator()(std::unique_ptr<int>&& input) const
  {
    std::cout << "Signaled " << *input.get();
  }
};

int main(int argc, char* argv[])
{
  boost::signals2::signal<void(std::unique_ptr<int>)> signal;

  signal.connect(MySlot());

  auto ptr = std::make_unique<int>(20);
  signal(std::move(ptr));
}

UPDATE I misunderstood the question. 更新我误解了这个问题。 You didn't want the handler types itself to be non-copyable, but rather their arguments. 您不希望处理程序类型本身是不可复制的,而是它们的参数。

The answer is: No, signals2 is is not move-aware. 答案是:不,signals2不支持移动。

NOTE In general, you should not have this situation, because many connections can subscribe to the same slot and you can only move from the parameter once. 注意通常,您不应该遇到这种情况,因为许多连接可以预订同一个插槽,并且只能从该参数移动一次。 In all likelihood, you're better of passing a copy/const reference: 在所有情况下,最好传递一个副本/常量引用:

#include <boost/signals2.hpp>
#include <iostream>
#include <memory>

struct MySlot
{
    void operator()(std::unique_ptr<int> const& input) const
    {
        std::cout << "Signaled " << *input.get();
    }
};

int main()
{
    boost::signals2::signal<void(std::unique_ptr<int> const&)> signal;

    signal.connect(MySlot());

    auto ptr = std::make_unique<int>(20);
    signal(ptr);
}

You can use the usual approaches: 您可以使用通常的方法:


Old answer: 旧答案:

Use std::ref or std::cref 使用std::refstd::cref

These wrappers transparently forward the function call operator. 这些包装器透明地转发函数调用运算符。

The onus of making sure the lifetime of the non-copyable callable exceeds that of the connection is on you. 确保不可复制的可调用对象的生命周期超过连接的生命周期是您的责任。

Make your own wrapper that's lifetime aware 使自己的包装器一生都知道

You can make a callable object wrapper that stores the non-copyable object and forwards the function call operator, like std::reference_wrapper<> did. 您可以像存储std::reference_wrapper<>一样,使可调用对象包装器存储不可复制的对象并转发函数调用运算符。 This time, though, you could store the object as a shared_ptr<> so the lifetime is automatically managed. 但是,这一次,您可以将对象存储为shared_ptr<>因此可以自动管理生命周期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM