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


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

最佳答案

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

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

关于c++ - C++绑定(bind)到weak_ptr无法正常工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25824039/

10-10 21:08
查看更多