使用FastDelegate进行分段故障

时间:2010-09-28 16:30:18

标签: c++ stl delegates crash segmentation-fault

我的测试代码出了问题。它编译得很好,但是当我尝试调用委托时,程序崩溃了。

#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)

1 个答案:

答案 0 :(得分:7)

RegisterFunction ("Foo", Function(&foo, 1)); 
                   ^ capital F
ExternalFuncs ["foo"] (5); 
                ^ lowercase f

由于地图中没有带有键"foo"的元素,ExternalFuncs["foo"]默认构造一个新的Function,将该默认构造对象插入到地图中,并返回对它的引用;然后在该对象上调用operator(),该对象尝试取消引用未初始化的Ptr成员变量。坏事发生了。