开发者

std::map< MyClass, std::vector<MyClass> > Segment fault. Oddness

开发者 https://www.devze.com 2023-03-19 18:16 出处:网络
开发者_运维问答SOLVED: Thanks figured it out thanks to dominic hamon. It all boils down to trying to call a function on a kinda null object. It could use parts of the object but not others.
开发者_运维问答

SOLVED: Thanks figured it out thanks to dominic hamon. It all boils down to trying to call a function on a kinda null object. It could use parts of the object but not others.

I had no idea that this could even happen.

Question

I have experienced an odd segmentation fault with a

std::map< IntVector3, std::vector<IntVector3> >. 

In my MyClass.hpp file I make this a private property:

std::map< IntVector3, std::vector< IntVector3 > > recurData;

In my MyClass.cpp file in the constructor for MyClass i can run

 std::vector< IntVector3 > pt;
 pt.push_back(IntVector3(1,2,3));
 recurData[IntVector3(1,2,3)] = pt;

This runs correctly and i don't get a fault.

Later in the program i call a function in MyClass that does the same thing, altering of recurData. Not in the constructor. This causes a segmentation fault. There is no other change to my knowledge that affects recurData.

The implementable of IntVector3 is: http://pastebin.com/Hc83xapk

There is a lot of extra operators that i added that are unneeded (>=,<=...). (I tried to follow the rule of 3)

The only real oddness is the < operator. This uses a std::string to compare. This quick hack should work for all x,y,z if they are under 99.

Thanks for the help, this has been driving me crazy.


Using a string to achieve a comparison function is (a) massively inefficient, and (b) broken. It will not provide you a strict-weak ordering, which is what is required for std::map. In particular, it is not going to be transitive, i.e. if a < b and b < c, it won't necessarily give you that a < c. This is going to totally mess up std::map.

A typical implementation of < would be something like:

bool operator< (const IntVector3 &a, const IntVector3 &b)
{
    if (a.z < b.z) { return true; }
    if (a.z > b.z) { return false; }
    if (a.y < b.y) { return true; }
    if (a.y > b.y) { return false; }
    return (a.x < b.x);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消