Cppcheck说char [256]应该在构造函数的初始化列表中初始化

Pat*_*ryk 3 c++ initialization c-strings initializer-list cppcheck

我用cppcheck检查了我的代码,它说我的char outStr[256]字段应该在构造函数的初始化列表中初始化.

warning: Member variable 'outStr' is not initialized in the constructor.
Run Code Online (Sandbox Code Playgroud)

此字段仅用于此方法:

const char* toStr(){
    sprintf(outStr,"%s %s", id.c_str(), localId.c_str());
    return outStr;
}
Run Code Online (Sandbox Code Playgroud)

添加c("")到初始化列表是否更好?还是cppcheck错了?或者还有其他方法可以解决这个问题吗?

Dan*_*äki 6

我是Cppcheck开发人员.

为所有未在构造函数中初始化的数据成员编写cppcheck警告.无论以后如何使用会员.

修复警告,您可以在构造函数中初始化您的数组.初始化第一个元素就足够了.例如,在构造函数中添加:

outStr[0] = 0;
Run Code Online (Sandbox Code Playgroud)

或者如果你更喜欢这样:

sprintf(outStr, "");
Run Code Online (Sandbox Code Playgroud)