2015-12-30 29 views
1

我有一個棘手的語法錯誤,我找不出來。我想運行一個函數委託,其中上下文是一個指向對象的指針。語法錯誤:使用指向對象的指針調用成員函數指針

語法錯誤:

((object)->*(ptrToMember)) // the compiler doesn't like the ->* 

Where object is of the type Component*

And ptrToMember is of the type void (Component::*EventCallback)()

下面是一個語法錯誤代碼:

typedef void (Component::*EventCallback)(); 

... 

std::weak_ptr<Component> wc(mySharedPtr); 
EventCallback ec = &Component::run; 

((wc.lock())->*(ec))(); // syntax error 
(wc.lock()->(*ec))(); // simpler version but still syntax error 

// This is ok, but is there any significant time or memory involved in this reference object creation? 
Component& wcc = *wc.lock(); 
(wcc.*ec)(); 
+0

太懶了搜索這個的副本所以在這裏'(object - > * ptrToMember)()' –

+0

哇,這麼多冗餘括號! –

回答

1

wc.lock()返回std::shared_ptr<Component>但你希望它返回一個原始Component*指針來代替。您無法撥打std::shared_ptr本身的->*。你要問它的Component*指針它持有,然後你可以使用->*操作上的指針,例如:

(wc.lock().get()->*ec)(); 

既然你正在處理一個std::weak_ptr,你使用它之前可能到期,

if (auto sptr = wc.lock()) { 
    (sptr.get()->*ec)(); 
} 
else { 
    // wc had expired 
} 
0

wc.lock()結果是shared_ptr:你嘗試之前訪問它,你應該確保Component對象鎖定後實際可用。這是智能指針與啞指針分開的少數情況之一。 shared_ptr沒有實現operator ->*,所以你的第一個語法不能工作。 (這不是語法錯誤,你只是想做點什麼shared_ptr不支持。)

你已經找到了解決方法。