[英]C++ - std::map.insert() segmentation fault
I get a segmentation fault when i try to insert into my map. 当我尝试插入地图时出现分割错误。
The function looks something like this: 该函数如下所示:
void add(std::string id, std::string name)
{
Asset asset(nullptr, false, name);
mAssets.insert(std::make_pair<std::string, Asset>(id,asset)); <-- This line gives segfault
}
mAssets is simply declared mAssets只需声明
std::map<assetID, Asset> mAssets;
And the Asset class is (sloppy) declared like this: Asset类的声明是(草率的),如下所示:
class Asset
{
public:
Asset(T* a, bool l, std::string f) : asset(a), loaded(l), filename(f)
{
}
Asset(const Asset& copy)
{
loaded = copy.loaded;
filename = copy.filename;
asset = new T();
*asset = *copy.asset;
}
~Asset()
{
delete asset;
}
Asset& operator=(const Asset& other)
{
Asset temp(other);
loaded = temp.loaded;
filename = temp.filename;
std::swap(asset,temp.asset);
return *this;
}
T* asset;
bool loaded;
std::string filename;
};
Your problem is here in your copy constructor: 您的问题在复制构造函数中:
asset = new T();
*asset = *copy.asset;
I will leave it to you to work out why... 我会把它留给你弄清楚为什么...
On your copy constructor you are derefferencing a null pointer: 在复制构造函数上,您要取消引用空指针:
*asset = *copy.asset
from 从
Asset asset(nullptr, false, name);
Verify your pointers asigments and avoid dereferencing null pointers: 验证您的指针分配,并避免取消引用空指针:
Asset(const Asset& copy)
{
loaded = copy.loaded;
filename = copy.filename;
if (copy.asset)
{
asset = new T(); // better may be asset = new T(copy)
*asset = *copy.asset;
}
else
{
asset = nullptr
}
}
*asset = *copy.asset; * asset = * copy.asset; //you should check whether asset is NULL or not then check for asset //您应该检查资产是否为NULL,然后检查资产
This is how your code will work: 这是代码的工作方式:
#include <iostream>
#include <map>
using namespace std;
template<class T>
class Asset
{
public:
Asset(T* a, bool l, std::string f) : asset(a), loaded(l), filename(f)
{
}
Asset(const Asset& copy)
{
cout<<"copy"<<endl;
loaded = copy.loaded;
filename = copy.filename;
asset = new T();
if(© != NULL)
{
if(copy.asset != NULL)
*asset = *(copy.asset);
}
}
~Asset()
{
delete asset;
}
Asset& operator=(const Asset& other)
{
Asset temp(other);
loaded = temp.loaded;
filename = temp.filename;
std::swap(asset,temp.asset);
return *this;
}
T* asset;
bool loaded;
std::string filename;
};
std::map <string,Asset<int> > mAssets;
void add(std::string id, std::string name)
{
Asset<int> asset(NULL, false, name);
mAssets.insert(std::make_pair<std::string, Asset<int> >(id,asset)); //<-- This line gives segfault
}
int main()
{
add("1","hi");
cout<<"run"<<endl;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.