std::map 自定义key类型,重写operator<() 没有严格弱序引起的“invalid comparator”


问题

现象

生产环境中偶发崩溃,调试时弹出以下弹窗:
在这里插入图片描述
定位问题为 map自定义key类型重写operator<() 没有严格弱序引起。

特征

  1. 编译正常,运行时偶发(取决于key值),容易让人以为是指针问题。

问题分析

严格弱序三要求

参考自: C++ 严格弱序

  1. 两个关键字不能同时“严格弱序”于对方
  2. 如果a“严格弱序”于b,且b“严格弱序”于c,则a必须“严格弱序”于c
  3. 如果存在两个关键字,任何一个都不“严格弱序”于另一个,则这两个关键字是相等的。

测试demo

  1. 根据业务代码bug输出demo如下:

    #include <map>
    
    struct StKey
    {
    	int account;
    	int type;
    
    	StKey(int account_, int type_):
    		account(account_),
    		type(type_)
    	{
    	}
    
    	bool operator<(const StKey & right) const
    	{
    #if 1
    		// 严格弱序
    		if (account != right.account)
    		{
    			return account < right.account;
    		}
    		
    		if (type != right.type )
    		{
    			return type < right.type ;
    		}
    		
    		return false;
    #else
    		// 非严格弱序,产生的原来实现
    		return account < right.account ? true :
    			type < right.type ? true : false;
    #endif
    	}
    };
    
    int main()
    {
    	std::map<StKey, std::string> partMap;
    
    	partMap[StKey(0, 1)] = "connection_2";
    
    	StKey partKey(1, 0);
    	if (partMap.count(partKey))
    	{
    		partMap[partKey] = "connection_3-1";
    	}
    
    	return 0;
    }
    
  2. 参考 C++ 严格弱序的做法,定义以下三个变量:

    StKey a(0, 2);
    StKey b(1, 0);
    StKey c(0, 1);
    

    严格弱序三要求 第二条结果如下:

    operator<()非严格弱序严格弱序
    a < btruefalse
    b < ctruefalse
    a < cfalsefalse
  3. 两种实现的区别

    • 上述非严格弱序实现中,如果a/b之间以account判断是否小于,b/c之间以type判断是否小于,a < c 并不是恒成立。
      - 严格弱序的实现是要求比较。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值