开发者

c++ std::set insert causing segmentation fault

All-

I can't quite figure out why this piece of code is resulting in a segmentation fault... Any help would be great.

#include <iostream>
#include <set>

using namespace std;

class A{
public:
    int _x;

    A(int x){
        _x = x;
    }
};

bool fncomp(A a1, A a2){
    return a1._x < a2._x;
}

int main(){
    bool(*fn_pt)(A,A) = fncomp;

    set<A, bool(*)(A,A)> testSet;
    for(int i=0; i<10; i++){
        cout << i <&l开发者_开发技巧t; endl;
        A a(i);
        testSet.insert(a);
    }
}

The output is:

0
1
Segmentation Fault


Well, look at your code. You declared a function fncomp, but are you really using that function anywhere? You initialize fn_pt with it, but fn_pt is not used anywhere. Doesn't it seem strange to you? How do you expect your testSet object to know that you want it to use your fncomp as the comparator, if you never ask your set object to use that function?

You declared your set testSet with an ordinary function pointer type bool(*)(A,A) as a comparator type. That's the type of the comparator. Now, you have to pass the actual value of the comparator to your set object through the constructor parameter

set<A, bool(*)(A,A)> testSet(fn_pt);

or

set<A, bool(*)(A,A)> testSet(fncomp);

(You don't really need that intermediate pointer fn_pt).

You forgot to do that, and the set object used the default constructor argument value for the comparator, which in this case is a null pointer. So, every time your testSet object tries to compare two elements, it performs a function call through a null pointer. No wonder it crashes.


Didn't you get a compiler warning about the unused variable fn_pt?

The variable testSet has an internal comparator of the specified type bool(*)(A,A). Since you didn't initialize it, it was default initialized as NULL. So when testSet tried to insert A(1), it tried to invoke a null function pointer to figure out which order is correct.

You probably meant:

set<A, bool(*)(A,A)> testSet(fn_pt);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜