0

我有一个简单的测试,我试图将一个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)

4

3 回答 3

1

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

function<void()> weakPrintValue = bind(callWeakFunction, ref(weakValue));
于 2014-09-13T14:20:41.217 回答
0

我不希望任何一个工作。在这两种情况下,您都在捕获weak_value它为空时的初始值。要受到后续分配的影响,您需要通过引用来捕获。所以在你需要的 lambda[&weak_value]和你需要的绑定中

bind(callWeakFunction, cref(weakValue));
于 2014-09-13T14:26:10.070 回答
0

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

于 2014-09-13T14:26:51.330 回答