使用 FastDelegate 的分段错误
我的测试代码有问题。它编译得很好,但是当我尝试调用委托时,程序崩溃了。
#include "..\libs\FastDelegate\FastDelegate.h"
#include <string>
#include <map>
#include <iostream>
typedef fastdelegate::FastDelegate1 <int, int> FuncPtr;
struct Function
{
FuncPtr Ptr;
int Param;
Function() {};
Function (FuncPtr Ptr_, int Param_): Ptr (Ptr_), Param (Param_) {};
int operator() (int xxx) {return Ptr(xxx);};
};
std::map <std::string, Function> ExternalFuncs;
bool RegisterFunction (const std::string& a, const Function b)
{
ExternalFuncs[a] = b;
return true;
}
int foo (int bar)
{
std::cout << "Jest gites";
return 0;
}
int main()
{
RegisterFunction ("Foo", Function(&foo, 1));
ExternalFuncs ["foo"] (5);
}
调用堆栈:
#0 00000000 0x00000000 in ??() (??:??)
#1 0041F209 fastdelegate::FastDelegate1<int, int>::operator() (this=0x3e256c, p1=5) (F:/Projekty/aaa/../libs/FastDelegate/FastDelegate.h:991)
#2 0041D774 Function::operator() (this=0x3e256c, xxx=5) (F:\Projekty\aaa\main.cpp:14)
#3 00401526 main() (F:\Projekty\aaa\main.cpp:34)
I've got a problem with my test code. It compiles well, but when I try to call delegate, program crashes.
#include "..\libs\FastDelegate\FastDelegate.h"
#include <string>
#include <map>
#include <iostream>
typedef fastdelegate::FastDelegate1 <int, int> FuncPtr;
struct Function
{
FuncPtr Ptr;
int Param;
Function() {};
Function (FuncPtr Ptr_, int Param_): Ptr (Ptr_), Param (Param_) {};
int operator() (int xxx) {return Ptr(xxx);};
};
std::map <std::string, Function> ExternalFuncs;
bool RegisterFunction (const std::string& a, const Function b)
{
ExternalFuncs[a] = b;
return true;
}
int foo (int bar)
{
std::cout << "Jest gites";
return 0;
}
int main()
{
RegisterFunction ("Foo", Function(&foo, 1));
ExternalFuncs ["foo"] (5);
}
Callstack:
#0 00000000 0x00000000 in ??() (??:??)
#1 0041F209 fastdelegate::FastDelegate1<int, int>::operator() (this=0x3e256c, p1=5) (F:/Projekty/aaa/../libs/FastDelegate/FastDelegate.h:991)
#2 0041D774 Function::operator() (this=0x3e256c, xxx=5) (F:\Projekty\aaa\main.cpp:14)
#3 00401526 main() (F:\Projekty\aaa\main.cpp:34)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于映射中没有带有键
"foo"
的元素,ExternalFuncs["foo"]
默认构造一个新的Function
,插入该函数默认构造对象放入映射中,并返回对其的引用;然后,您对该对象调用operator()
,该对象尝试取消引用未初始化的Ptr
成员变量。坏事发生了。Since there is no element in the map with the key
"foo"
,ExternalFuncs["foo"]
default constructs a newFunction
, inserts that default constructed object into the map, and returns a reference to it; you then calloperator()
on that object, which attempts to dereference the uninitializedPtr
member variable. Bad things happen.