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

Syntax Error: Call Member Function Pointer using Pointer to Object

本文关键字:指针 调用 成员 函数 对象 错误 语法      更新时间:2023-10-16

我有一个棘手的语法错误,我无法解决。我正在尝试运行一个函数委托,其中上下文是指向对象的指针。

语法错误:

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

其中object属于Component* 类型

ptrToMember属于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)();

wc.lock()返回一个std::shared_ptr<Component>,但您希望它返回一个原始的Component*指针。不能在std::shared_ptr本身上调用->*。你必须向它询问它所持有的Component*指针,然后你可以在该指针上使用->*运算符,例如:

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

由于您正在处理一个std::weak_ptr,它可能在您使用它之前就过期了,因此在尝试访问它之前,您应该确保Component对象在锁定后实际上是可用的:

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

wc.lock()的结果是shared_ptr。这是为数不多的智能指针与哑指针不同的情况之一。shared_ptr没有实现operator ->*,所以您的第一个语法无法工作。(这不是语法错误,你只是想做shared_ptr不支持的事情。)

不过你已经找到了一个变通办法。