c++ - 如何将仿函数与 bind 和 weak_ptr 结合使用

标签 c++ c++11

如何更改下面的代码以使用 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)
{
}

最佳答案

你可以使用 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);
}

关于c++ - 如何将仿函数与 bind 和 weak_ptr 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37744647/

相关文章:

c++:自旋锁或互斥比较(简单计算)

c++ - 将指向 vector 的指针推回然后修改其值会影响插入的值。我应该怎么做呢?

c++ - std::find_if_not() 返回什么类型?

c++ - 从 arm 程序集调用 c 函数时堆的地址发生了变化?

c++ - SetThreadAffinityMask 无效

c++ - C中实现的平均直流估计器的解释

c++ - 通用实现获取类型列表的大小

c++ - malloc 中的 void* 与 operator new

c++ - C++ copy_if、transform 等的函数版本

c++ - 是否有 C++ 方法允许在不创建临时变量的情况下多次使用函数指针?