简体   繁体   中英

Suppress compiler warning

C++ how to suppress this warning message when compiling?

Warning:

regen.cpp:531:30: warning: 'void* memset(void*, int, size_t)' clearing an object of type 'REGEN' {aka 'struct regen'} with no trivial copy-assignment; use assignment or value-initialization instead [-Wclass-memaccess]
  531 |   memset(&tmp, 0, sizeof(tmp));

Code:

REGEN tmp;
memset(&tmp, 0, sizeof(tmp));

You must clear your object's data individually within a constructor(or any user-defined init function). Do this:

typedef struct regen {
    regen() {
        memset(_someData, 0, 128);
    }
    char _someData[128];
} REGEN;

In C++, you must not overwrite the bytes of an object directly like you do in C because unlike C, C++ compiler generates a little more complex low-level information(text/data) from its source. For example, an object of some class/struct may contain an additional data structure called for providing runtime polymorphism feature and this data might get corrupted upon performing memset() on the object directly.的附加数据结构,用于提供运行时多态性功能,并且在直接对 object 执行 memset() 时,该数据可能会损坏。
As a reference, refer to this documentation of GCC( C++ dialect options(GCC) ). Go to the -Wclass-memaccess section where it mentions the following:

-Wclass-memaccess (C++ and Objective-C++ only)

Warn when the destination of a call to a raw memory function such as memset or memcpy is an object of class type, and when writing into such an object might bypass the class non-trivial or deleted constructor or copy assignment, violate const-correctness or encapsulation, or corrupt virtual table pointers. Modifying the representation of such objects may violate invariants maintained by member functions of the class. For example, the call to memset below is undefined because it modifies a non-trivial class object and is, therefore, diagnosed. The safe way to either initialize or clear the storage of objects of such types is by using the appropriate constructor or assignment operator, if one is available.

std::string str = "abc";
memset (&str, 0, sizeof str);

The -Wclass-memaccess option is enabled by -Wall. Explicitly casting the pointer to the class object to void * or to a type that can be safely accessed by the raw memory function suppresses the warning.

I am no C++ god but I hope this helps in some way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM