Henningsson Henningsson - 1 month ago 13
C++ Question

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

std::map<assetID, Asset> mAssets;


And the Asset class is (sloppy) declared like this:

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;
};

Nim Nim
Answer

Your problem is here in your copy constructor:

  asset    = new T();
  *asset   = *copy.asset;

I will leave it to you to work out why...