我正在处理包含C和C ++代码的模块。问题是我收到以下禁止的警告。我提供了引起警告的代码。
warning: 'void* memset(void*, int, size_t)' clearing an object of type 'struct OtherStructure_s ' with no trivial copy-assignment; use assignment or value-initialization instead [-Wclass-memaccess]\n")
struct TEST {
explicit TEST();
OtherStructure_s _otherStructure;
};
TEST::TEST(){
memset(&_otherStructure, 0, sizeof(OtherStructure_s));
}
删除该警告的最佳解决方案是什么?如果我像在构造函数中一样初始化结构TEST::TEST():_otherStructure(){}
那将是一个好的解决方案吗?
OtherStructure_s
没有trivial copy assignment operator。您不能使用memset
。该类可能还会分配一些其他资源,例如堆内存。
您不需要TEST::TEST():_otherStructure(){}
。 TEST
的默认构造函数将默认构造_otherStructure
。最好的解决方案是删除构造函数。
理想情况下,您应该在构造函数中初始化结构。但是,如果出于某些原因需要执行memset,则可以尝试以下操作:
TEST::TEST(){
memset((char *)&_otherStructure, 0, sizeof(OtherStructure_s));
}