SL.con.4:不要对不能直接拷贝的参数使用memset或memcpy
Doing so messes the semantics of the objects (e.g., by overwriting a vptr).
这样做会搞乱对象的语义(例如覆盖虚函数指针)。
Note(注意)
Similarly for (w)memset, (w)memcpy, (w)memmove, and (w)memcmp
(w)memset, (w)memcpy, (w)memmove, and (w)memcmp的情况也类似。
Example(示例)
struct base {
virtual void update() = 0;
};
struct derived : public base {
void update() override {}
};
void f(derived& a, derived& b) // goodbye v-tables
{
memset(&a, 0, sizeof(derived));
memcpy(&a, &b, sizeof(derived));
memcmp(&a, &b, sizeof(derived));
}
Instead, define proper default initialization, copy, and comparison functions
正确的方法是定义适当的默认初始化,拷贝和比较函数
void g(derived& a, derived& b)
{
a = {}; // default initialize
b = a; // copy
if (a == b) do_something(a, b);
}
TODO Notes(待办记录):
原文链接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#slcon4-dont-use-memset-or-memcpy-for-arguments-that-are-not-trivially-copyable