gpt4 book ai didi

c++ - 使用 FastDelegate 的段错误

转载 作者:太空宇宙 更新时间:2023-11-04 15:28:03 27 4
gpt4 key购买 nike

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

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

最佳答案

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

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

关于c++ - 使用 FastDelegate 的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3814969/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com