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