Sai*_*ruS 5 c++ stdmap bad-alloc
我面临着std :: map的问题。出于未知原因,有时插入映射会导致“分配错误”异常。
以下是我用于插入地图的函数。
BOOL Add2WaitList(Object<LPVOID> *newObj)
{
try
{
_set_se_translator( trans_func );
m_syncWQ.Lock();
if (m_waitingQueue.count(newObj->uid)>0)
{
m_syncWQ.Unlock();
return FALSE;
}
m_waitingQueue[newObj->uid] = *newObj; <-- failing here
m_syncWQ.Unlock();
return TRUE;
}
catch(std::exception &ex){
...
}
catch(SE_Exception &e){
...
}
catch(...){
...
}
}
Run Code Online (Sandbox Code Playgroud)
有人可以告诉我如何解决吗?
注意:我无法确定重现它的步骤。
提前THX!
添加有关对象和地图的详细信息:
template <typename T>
struct Object{
public:
void Kill()
{
if (response!=NULL)
delete response;
if (object!=NULL)
delete object;
}
enum objType;
std::string uid;
enum status;
double p;
enum execType;
T object;
LPVOID response;
};
std::map<std::string,Object<LPVOID>> m_waitingQueue;
Run Code Online (Sandbox Code Playgroud)
异常std::bad_alloc意味着“operator new失败”。因此,要么operator new被operator*on调用newObj(我们对此一无所知),要么被映射的插入运算符调用(可能性极大)。
具体来说,当您operator[]使用某个参数 k 调用地图时
如果 k 与容器中任何元素的键都不匹配,则该函数将插入具有该键的新元素并返回对其映射值的引用。请注意,即使没有为元素分配映射值(该元素是使用其默认构造函数构造的),这始终会将容器大小增加一。
(如此处记录)。
Map::operator[]为失败提供强有力的保障:
Strong guarantee: if an exception is thrown, there are no changes in the container.
Run Code Online (Sandbox Code Playgroud)
但不保证不抛出异常(即它不提供不抛出保证)。
引发异常的原因operator new可能有不同的性质。然而,这一切都归结为:
throws bad_alloc if it fails to allocate storage.
Run Code Online (Sandbox Code Playgroud)
也就是说,正如 JamesKanze 在评论中建议的那样:
std::bad_alloc 的另一个可能原因是未定义的行为。例如,如果他破坏了自由空间竞技场。实际上,如果他确实内存不足,失败的分配会有所不同。如果系统地在这里,我会怀疑 Object 的复制构造函数有问题,而不是其他任何事情。
这意味着operator new由于程序其他部分的一些错误而无法分配存储。您可以通过在调用operator[]. 如果虚拟分配没有失败,您可以很有把握地说复制构造函数存在错误。