仅在一个构造函数上的类成员初始化程序中的隐式常量转换[-Werror = overflow]中的溢出

问题描述 投票:0回答:1

有几个类似的问题,但这可能是由于gcc编译器中的一个错误引起的。唯一的常量是参数vvalue。我已更改为char *,但仍收到相同的编译器警告。

这是具有类的第三方代码(不显示名称空间等。仅显示相关部分

class Value {
public:
    ....
    Value(double value);
    Value(const char *vvalue);
    ....
private:
        struct CommentInfo {
          CommentInfo();
           ~CommentInfo();
          void setComment( const char *text );
           char *comment_;
      };

        union ValueHolder {
          Int int_;
           UInt uint_;
           double real_;
           bool bool_;
           char *string_;
 #ifdef JSON_VALUE_USE_INTERNAL_MAP
           ValueInternalArray *array_;
          ValueInternalMap *map_;
 #else
         ObjectValues *map_;
 #endif
        } value_;
        ValueType type_ : 8;
        int allocated_ : 1;     // Notes: if declared as bool, bitfield is useless.
 #ifdef JSON_VALUE_USE_INTERNAL_MAP
       unsigned int itemIsUsed_ : 1;      // used by the ValueInternalMap container.
        int memberNameIsStatic_ : 1;       // used by the ValueInternalMap container.
 #endif
        CommentInfo *comments_;
     };

};

/// class definition
 316 Value::Value( double value )
 317    : type_( realValue )
 318    , comments_(nullptr)
 319 # ifdef JSON_VALUE_USE_INTERNAL_MAP
 320    , itemIsUsed_( 0 )
 321 #endif
 322 {
 323    value_.real_ = value;
 324 }
 325 
 326 Value::Value(const char *vvalue)
 327    : type_(stringValue), allocated_(true),
 328       comments_(nullptr)
 329 #ifdef JSON_VALUE_USE_INTERNAL_MAP
 330       , itemIsUsed_( 0 )
 331 #endif 
 332 {     
 333    value_.string_ = duplicateStringValue(vvalue);
 334 }     

[当我们使用-Werror -Wall运行时,我们仅在构造函数接受输入而其他的构造函数不接受comment_成员的情况下才收到以下错误消息:

json_value.cpp:328:24: error: overflow in implicit constant conversion [-Werror=overflow]
       comments_(nullptr)
                        ^

足够奇怪的是,(双值)版本的构造函数上不会发生警告。我凝视了很长时间的代码,看不到可以更改以消除此警告的地方。

这可能与位字段有关:

 309 Value::Value( double value )
 310    : type_( realValue ),
 311    //allocated_(true), // adding this caused overflow issue
 312    //allocated_(1), // adding this caused overflow issue
 313    //allocated_(0), // this eliminates overflow issue
 314    allocated_(false), // this eliminates overflow issue
 315    comments_(nullptr)

[我发现,警告与上一个类成员中的位字段有关:alocated_,它是布尔值的1位。不确定代码是不好的做法还是什么。

c++ gcc compiler-warnings
1个回答
1
投票

位字段allocated_可以容纳两个值。在您的实现中,它们是0-1See this question for why.您正在使用true对其进行初始化,这将转换为1,这将溢出。开启-Wconversion可以很好地说明这一点:

警告:从'int'到'signed char:1'的转换将值从'1'变为'-1'[-Wconversion]

更新:溢出警告也有此详细信息。两者都具有从gcc 8.1起的详细信息。该第三方库似乎是jsoncpp,并且此错误似乎已在2015年1月24日(ref)的commit 2bc6137a中修复,并包含在2015年2月11日发布的v1.4.0(ref)中。

© www.soinside.com 2019 - 2024. All rights reserved.