我有一個簡單的測試,我試圖綁定一個weak_ptr參數到一個全局函數,它接受一個weak_ptr,並在內部指針仍然有效時調用一個方法。C++綁定到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)
謝謝,通過引用捕獲是問題。因爲這是識別這個問題的第一個答案,我會接受這個答案。謝謝 – kman 2014-09-13 14:34:00