清除类型为'struct'的对象,且没有琐碎的拷贝分配;使用赋值或值初始化代替

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

我正在处理包含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(){}那将是一个好的解决方案吗?

c++ struct constructor memset
2个回答
1
投票

OtherStructure_s没有trivial copy assignment operator。您不能使用memset。该类可能还会分配一些其他资源,例如堆内存。

您不需要TEST::TEST():_otherStructure(){}TEST的默认构造函数将默认构造_otherStructure。最好的解决方案是删除构造函数。


-2
投票

理想情况下,您应该在构造函数中初始化结构。但是,如果出于某些原因需要执行memset,则可以尝试以下操作:

TEST::TEST(){
  memset((char *)&_otherStructure, 0, sizeof(OtherStructure_s));
}
© www.soinside.com 2019 - 2024. All rights reserved.