前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则SL.con.4:不要对不能直接拷贝的参数使用memset或memcpy

C++核心准则SL.con.4:不要对不能直接拷贝的参数使用memset或memcpy

作者头像
面向对象思考
发布2020-10-30 11:30:26
5980
发布2020-10-30 11:30:26
举报

SL.con.4: don't use memset or memcpy for arguments that are not trivially-copyable

SL.con.4:不要对不能直接拷贝的参数使用memset或memcpy

Reason(原因)

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(示例)

代码语言:javascript
复制
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

正确的方法是定义适当的默认初始化,拷贝和比较函数

代码语言:javascript
复制
void g(derived& a, derived& b)
{
    a = {};    // default initialize
    b = a;     // copy
    if (a == b) do_something(a, b);
}
Enforcement(实施建议)
  • Flag the use of those functions for types that are not trivially copyable 标记使用针对不可简单复制的类型使用上述函数的情况。

TODO Notes(待办记录):

  • Impact on the standard library will require close coordination with WG21, if only to ensure compatibility even if never standardized. 对标准库的冲击要求和WG21进行紧密合作,如果只确保兼容性,恐怕永远也无法标准化。
  • We are considering specifying bounds-safe overloads for stdlib (especially C stdlib) functions like memcmp and shipping them in the GSL. 我们正在考虑为类似memcmp的stdlib(特别是C标准库)函数定义重载版本并发布到GSL中。
  • For existing stdlib functions and types like vector that are not fully bounds-checked, the goal is for these features to be bounds-checked when called from code with the bounds profile on, and unchecked when called from legacy code, possibly using contracts (concurrently being proposed by several WG21 members). 对于存在的没有完全进行边界检查的标准库函数和类型,例如vector,目标是被边界准则群组有效的代码调用时可以进行边界检查,被历史代码调用时不检查。实现方式有可能是使用契约(同时被多位WG21成员建议)

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#slcon4-dont-use-memset-or-memcpy-for-arguments-that-are-not-trivially-copyable

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-10-20,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • SL.con.4: don't use memset or memcpy for arguments that are not trivially-copyable
  • Reason(原因)
    • Enforcement(实施建议)
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档