Search code examples
c++structconstructormemset

clearing an object of type 'struct ' with no trivial copy-assignment; use assignment or value-initialization instead


I am working on a module containing C and C++ codes. The problem is that I am getting the following forbidden warning. I provided the code that Is causing that warning.

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));
}

What is the best solution to remove that warning? If I initialize the structure in the constructor as if TEST::TEST():_otherStructure(){} will that be a good solution?


Solution

  • OtherStructure_s doesn't have a trivial copy assignment operator. You can't use memset. Probably the class allocates some other resources like heap memory.

    You don't need TEST::TEST():_otherStructure(){}. The default constructor of TEST will default construct _otherStructure. The best solution is to remove the constructor.