gpt4 book ai didi

c++ - MacOS X- C++ 中的段错误 11

转载 作者:行者123 更新时间:2023-11-28 03:30:15 25 4
gpt4 key购买 nike

当我运行以下代码时出现“segmentation fault 11”错误。代码实际上可以编译,但我在运行时遇到错误。

//** Terror.h **

#include <iostream>
#include <string>
#include <map>

using std::map;
using std::pair;
using std::string;

template<typename Tsize>
class Terror
{
public:
//Inserts a message in the map.
static Tsize insertMessage(const string& message)
{
mErrorMessages.insert( pair<Tsize, string>(mErrorMessages.size()+1, message) );
return mErrorMessages.size();
}

private:
static map<Tsize, string> mErrorMessages;
};

template<typename Tsize>
map<Tsize,string> Terror<Tsize>::mErrorMessages;

//** 错误.h **

#include <iostream>
#include "Terror.h"

typedef unsigned short errorType;
typedef Terror<errorType> error;
errorType memoryAllocationError=error::insertMessage("ERROR: out of memory.");

//** main.cpp **

#include <iostream>
#include "error.h"
using namespace std;

int main()
{
try
{
throw error(memoryAllocationError);
}
catch(error& err)
{
}
}

我调试了代码,当消息被插入静态映射成员时发生了错误。一个观察是,如果我把这条线:

errorType memoryAllocationError=error::insertMessage("ERROR: out of memory.");

在“main()”函数内而不是在全局范围内,那么一切正常。但我想在全局范围内扩展错误消息,而不是在本地范围内。该映射被定义为静态的,因此“错误”的所有实例都共享相同的错误代码和消息。你知道我怎样才能得到这个或类似的东西吗。

非常感谢。

最佳答案

当我尝试在 Mac OS X 10.7 上运行我为 OS X 10.8 编译的应用程序时,我遇到了同样的问题。

将目标设置为 10.7 解决了这个问题。该应用程序在 10.7 和 10.8 OS X 环境中运行良好。

关于c++ - MacOS X- C++ 中的段错误 11,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12765735/

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