简体   繁体   中英

Syntax Error: Call Member Function Pointer using Pointer to Object

I have a tricky syntax error which I cannot figure out. I am trying to run a function delegate where the context is a pointer to an object.

Syntax error:

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

Where object is of the type Component*

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

Below is the code with the syntax error:

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)();

wc.lock() returns a std::shared_ptr<Component> but you are expecting it to return a raw Component* pointer instead. You cannot call the ->* on the std::shared_ptr itself. You have to ask it for the Component* pointer it is holding, and then you can use the ->* operator on that pointer, eg:

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

Since you are dealing with a std::weak_ptr , which could expire before you use it, you should make sure the Component object is actually available after locking before you try to access it:

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

The result of wc.lock() is a shared_ptr . This is one of the few cases where the smart pointer diverges from a dumb pointer. shared_ptr does not implement operator ->* , so your first syntax can't work. (It's not a syntax error, you're just trying to do something shared_ptr doesn't support.)

You've found a workaround though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM