seg fault/undefined std::map 的比较函数中的行为
seg fault/undefined behavior in comparator function of std::map
今天这让我很困惑。
我无法理解为什么下面的代码在最终插入 test_map 时出现段错误。使用 emplace()、insert() 都按预期工作,但使用 [] 运算符失败。我已经阅读了 [] 的相关 C++ 文档,但下面观察到的行为似乎与我所阅读的不符。
我在 GDB 中单步执行并注意到在比较器函数中尝试比较字符串时它失败了。
#include <iostream>
#include <map>
#include <iostream>
class Testkey {
public:
std::string s1;
int64_t id;
Testkey(const char* s1_, int64_t id_): s1(s1_), id(id_) {}
bool operator<(const Testkey& rhs) const {
if (s1 < rhs.s1)
return true;
if (id < rhs.id)
return true;
return false;
}
};
int main() {
Testkey i1("69739", 748072524);
Testkey i2("69728", 52608624);
Testkey i3("69725", 750212380);
Testkey i4("68988", 55027788);
std::map<Testkey, int> test_map;
test_map[i1] = 1;
test_map[i2] = 2;
test_map[i3] = 3;
std::cout << "hmm.." << std::endl;
test_map[i4] = 4; // seg faults here in comparator function...
std::cout << "done" << std::endl;
return 0;
}
你的比较功能坏了。你可能是这个意思:
bool operator<(const Testkey& rhs) const {
if (s1 < rhs.s1)
return true;
if (s1 > rhs.s1)
return false;
if (id < rhs.id)
return true;
return false;
}
用于 std::map
的比较函数必须定义要插入或比较的对象的 strict weak ordering,而您的函数不需要,因为 i3<i2
和 i2<i3
是真的。
今天这让我很困惑。
我无法理解为什么下面的代码在最终插入 test_map 时出现段错误。使用 emplace()、insert() 都按预期工作,但使用 [] 运算符失败。我已经阅读了 [] 的相关 C++ 文档,但下面观察到的行为似乎与我所阅读的不符。
我在 GDB 中单步执行并注意到在比较器函数中尝试比较字符串时它失败了。
#include <iostream>
#include <map>
#include <iostream>
class Testkey {
public:
std::string s1;
int64_t id;
Testkey(const char* s1_, int64_t id_): s1(s1_), id(id_) {}
bool operator<(const Testkey& rhs) const {
if (s1 < rhs.s1)
return true;
if (id < rhs.id)
return true;
return false;
}
};
int main() {
Testkey i1("69739", 748072524);
Testkey i2("69728", 52608624);
Testkey i3("69725", 750212380);
Testkey i4("68988", 55027788);
std::map<Testkey, int> test_map;
test_map[i1] = 1;
test_map[i2] = 2;
test_map[i3] = 3;
std::cout << "hmm.." << std::endl;
test_map[i4] = 4; // seg faults here in comparator function...
std::cout << "done" << std::endl;
return 0;
}
你的比较功能坏了。你可能是这个意思:
bool operator<(const Testkey& rhs) const {
if (s1 < rhs.s1)
return true;
if (s1 > rhs.s1)
return false;
if (id < rhs.id)
return true;
return false;
}
用于 std::map
的比较函数必须定义要插入或比较的对象的 strict weak ordering,而您的函数不需要,因为 i3<i2
和 i2<i3
是真的。