【问题标题】:C++ bind to weak_ptr not workingC ++绑定到weak_ptr不起作用
【发布时间】:2014-09-13 14:11:30
【问题描述】:

我有一个简单的测试,我试图将一个weak_ptr 参数绑定到一个采用weak_ptr 的全局函数,并在支持指针仍然有效时调用一个方法。

当我使用弱指针创建 lambda 时,这似乎有效。如果我使用weak_ptr 直接调用全局方法,它也可以工作。但是,如果我提前将全局函数绑定到weak_ptr,它似乎不起作用。以下淡化代码说明了这个问题。

我一定错过了一些简单的东西。有什么线索吗?

#include <iostream>
#include <functional>
#include <algorithm>
#include <memory>

using namespace std;

class MyValue : public enable_shared_from_this<MyValue>
{
    public:
        MyValue (int i)
        {
            value = i;
        }

        ~MyValue()
        {
        }

        int getValue() { return value; }

        void printValue() { cout << value << endl; }

    private:

        int value;
};

void callWeakFunction (weak_ptr<MyValue> weakValue)
{
    shared_ptr<MyValue> strongPtr = weakValue.lock();

    if (strongPtr)
    {
        strongPtr->printValue();
    }
    else
    {
        cout << "Sorry, your backing pointer is gone" << endl;
    }
}

int main()
{
    weak_ptr<MyValue> weakValue;

    // Try binding a global function to the weak pointer, doesn't seem to work
    function<void()> weakPrintValue = bind(callWeakFunction, weakValue);

#if 0
    // Create a lambda - this works fine
    function<void()> weakPrintValue ([&weakValue]()
                       {
                           shared_ptr<MyValue> ptr = weakValue.lock();
                           if(ptr)
                           {
                               ptr->printValue();
                           }
                           else
                           {
                               cout << "Sorry, backing pointer is gone" << endl;
                           }
                       });
#endif

    {
        shared_ptr<MyValue> value = make_shared<MyValue>(7);

        weakValue = value;

        // Backing pointer is present
        weakPrintValue();    // This does not work, but callWeakFunction (weakValue) works fine
    }

    // No backing pointer
    weakPrintValue();
}

结果输出:

Sorry, your backing pointer is gone
Sorry, your backing pointer is gone

期望第一个weakPrintValue打印值(7)

【问题讨论】:

    标签: c++ bind weak-ptr


    【解决方案1】:

    我认为您想将 weak_ptr 包装在 ref() 中以懒惰地评估它:

    function<void()> weakPrintValue = bind(callWeakFunction, ref(weakValue));
    

    【讨论】:

    • 谢谢,通过引用捕获是问题所在。由于这是识别此问题的第一个答案,因此我将接受此答案。谢谢
    【解决方案2】:

    我不希望两者都能工作。在这两种情况下,您都会在 weak_value 为空时捕获它的初始值。要受到后续分配的影响,您需要通过引用来捕获。因此,在 lambda 中您需要 [&amp;weak_value],并且对于您需要的绑定

    bind(callWeakFunction, cref(weakValue));
    

    【讨论】:

    • 你说得对,我的 lambda 中有一个复制粘贴错误,我已修复。我看到了按引用捕获的要求,这是有道理的。
    【解决方案3】:

    我相信bind() 按价值捕获weakValue。它返回具有自己的weakValue 副本的结果对象。当您更改本地 weakValue 时,它不会影响 bind() 返回的对象内部的副本。

    【讨论】:

      猜你喜欢
      • 2012-07-25
      • 1970-01-01
      • 2011-08-19
      • 1970-01-01
      • 2012-04-15
      • 2010-12-08
      • 2015-05-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多