2014-09-13 72 views
0

我有一個簡單的測試,我試圖綁定一個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)

回答

1

我想你想要包裝REF()的weak_ptr的延遲計算它的價值:

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

謝謝,通過引用捕獲是問題。因爲這是識別這個問題的第一個答案,我會接受這個答案。謝謝 – kman 2014-09-13 14:34:00

0

我不希望任何工作。在這兩種情況下,您都會在空的時候捕獲初始值weak_value。受後續分配的影響,您需要通過引用來捕獲。所以在lambda需要[&weak_value],並綁定需要

bind(callWeakFunction, cref(weakValue)); 
+0

你是對的,我在我修正的lambda中有一個複製粘貼錯誤。我看到通過引用要求捕獲,是有道理的。 – kman 2014-09-13 14:33:12

0

我相信bind()捕捉weakValue的價值。它返回的結果對象具有它自己的weakValue副本。當您更改本地weakValue時,它不會影響bind()返回的對象內的副本。