简体   繁体   English

语法错误:使用指向对象的指针调用成员函数指针

[英]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* 其中object的类型为Component*

And ptrToMember is of the type void (Component::*EventCallback) () 而且ptrToMember的类型为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. wc.lock()返回一个std::shared_ptr<Component>但是您希望它返回一个原始的Component*指针。 You cannot call the ->* on the std::shared_ptr itself. 您不能在std::shared_ptr本身上调用->* You have to ask it for the Component* pointer it is holding, and then you can use the ->* operator on that pointer, eg: 您必须要求它提供它持有的Component*指针,然后可以对该指针使用->*运算符,例如:

(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: 由于您要处理的std::weak_ptr可能在使用前过期,因此在尝试访问它之前,应确保在锁定后Component对象实际上可用:

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

The result of wc.lock() is a shared_ptr . wc.lock()的结果是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. shared_ptr没有实现operator ->* ,因此您的第一种语法无法工作。 (It's not a syntax error, you're just trying to do something shared_ptr doesn't support.) (这不是语法错误,您只是在尝试做shared_ptr不支持的操作。)

You've found a workaround though. 不过,您已经找到了解决方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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