[英]C++ bind to weak_ptr not working
我有一个简单的测试,在该测试中,我试图将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)
我认为您想将weak_ptr包装在ref()中以懒惰地对其进行评估:
function<void()> weakPrintValue = bind(callWeakFunction, ref(weakValue));
我不希望两者都能起作用。 在这两种情况下,您都将在weak_value
为空时捕获其初始值。 要受到后续分配的影响,您需要改为通过引用捕获。 因此,在lambda中,您需要[&weak_value]
,对于绑定,您需要
bind(callWeakFunction, cref(weakValue));
我相信bind()
可以按值捕获weakValue
。 它返回具有自己的weakValue
副本的结果对象。 更改本地weakValue
它不会影响bind()
返回的对象内部的副本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.