我有一个函数 Foo 和一个类 CDelegate。
typedef void (*typeFctPtr)(void*);
void Foo(void* dummy)
{
cout << "Foo\n";
}
class CDelegate
{
public:
CDelegate (const typeFctPtr& f_ref_Wrapper, void* f_pvSubscriber)
: m_ref_Wrapper(f_ref_Wrapper), m_pvSubscriber(f_pvSubscriber)
{
}
inline void operator () () const
{
(*m_ref_Wrapper)(0);
}
inline void operator=(const CInterruptDelegate& D)
{
}
private:
void* m_pvSubscriber;
const typeFctPtr& m_ref_Wrapper;
};
第二个类有一个静态成员 static CDelegate m_Delegate;
我使用这样的构造函数初始化它:
CInterruptDelegate CSpi1::m_Delegate(FreeFunction, 0);
我想通过调用静态对象的 () 运算符来调用 Foo
:CSpi1::m_Delegate();
我在 (*m_ref_Wrapper)(0);
处遇到异常
语法有问题吗?我不太确定我尝试做的事情是否可行。我有一个可行的解决方案,其中 CDelegate
的构造函数不采用函数指针的 const 引用,而是采用函数指针本身。然后我可以毫无问题地调用 () 运算符中的函数。我想使用 const 引用,因为无法优化函数指针调用,我希望通过 const 引用的调用可以,因为一切都应该在编译时知道。
最佳答案
您持有指向函数指针的引用(并且该指针是一个临时指针,在您使用它时已被销毁,因此出现严重错误)。
尝试将您的 typedef 更改为函数类型:
typedef void typeFct(void*);
...
const typeFct & m_ref_Wrapper;
然后使用您现有的代码,您最终会得到一个函数的引用,这样就没问题了。或者您可以存储指向函数的指针 - const typeFct *
。
无论哪种情况,调用都可以是m_ref_Wrapper(0)
。
一般来说,我更喜欢 typedef 函数类型,而不是指针或引用,只是因为语法不那么难看。
关于c++ - 对函数指针的 const 引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6536748/