【问题标题】:How to combine using functor with bind and weak_ptr如何将仿函数与 bind 和 weak_ptr 结合使用
【发布时间】:2016-06-10 09:27:05
【问题描述】:

如何更改下面的代码以使用 weak_ptr 而不是 shared_ptr 并保持指定方法名称的能力(如在 std::bind 中所做的那样)?似乎 std::bind 不支持weak_ptr,因为它需要检查weak_ptr。

void foo::a()
{
  m_class.do1(
    std::function<void(int)>(
      std::bind(&foo::b, shared_from_this(), std::placeholders::_1)));
}

void foo::b(int i)
{
}

【问题讨论】:

  • 这个假设绑定的语义是什么?
  • 不确定我是否理解这个问题。我们想要的是,如果weak_ptr::lock 返回一个有效的shared_ptr,则调用函子。
  • 如果 lock() 没有返回有效的共享指针,你会怎么做?
  • do是C++中的关键字,不能是函数名。
  • 如果锁没有返回一个有效的共享指针,我什么也不做。

标签: c++ c++11


【解决方案1】:

你可以使用 lambda:

void foo::a()
{
    std::weak_ptr<foo> w {shared_from_this()};
    auto l = [w](int i) {
        auto ptr = w.lock();
        if (ptr) {
            ptr->b(i);
        }
    };
    m_class.run(l);
}

【讨论】:

  • 这看起来很有趣。会做一些测试。
  • 您可以将变量 ptr 设置为 if 语句的局部变量。
猜你喜欢
  • 2014-12-17
  • 2012-10-27
  • 2019-08-16
  • 1970-01-01
  • 2017-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多