语法错误:使用指向对象的指针调用成员函数指针
Syntax Error: Call Member Function Pointer using Pointer to Object
我有一个棘手的语法错误,我无法解决。我正在尝试运行一个函数委托,其中上下文是指向对象的指针。
语法错误:
((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
不支持的事情。)
不过你已经找到了一个变通办法。
相关文章:
- 为什么使用 "this" 指针调用派生成员函数?
- 当使用通配符和null指针调用函数时,对输出的说明
- Visual c ++,使用字符串引用/指针调用 dll 函数
- 使用基类指针调用基类的值构造函数的语法是什么?
- 是否可以使用函数指针调用虚拟析构函数?
- 使用C++指针调用 python 函数
- 如何使用接口指针调用方法,该指针是其具体类的一部分,而不是接口的一部分
- 是否可以使用非常量指针调用非常量函数,以及当两个unique_ptrs指向同一个对象时程序的行为方式?
- 在将派生类指针类型转换为派生类指针后,从基类指针调用派生类函数
- 通过指针调用模板类成员函数 [为什么这是有效的 c++]?
- 从带有参数的基函数指针调用基方法
- 使用唯一指针调用函数会使我的程序崩溃
- C++::在构造函数退出之前通过指针调用成员函数
- 有没有办法在没有虚拟的情况下使用基类指针调用派生类函数
- 什么时候用指针调用C++类构造函数
- C++ - 使用变量指针调用函数
- 为什么我可以通过野生指针调用成员函数
- 从指针调用方法时出现分段错误
- 为什么使用指向函数的指针调用虚函数时不需要指针"this"?
- C++ abort() 在函数内的抽象类对象指针调用上