memcpy函数_不要对不能直接拷贝的参数使用memset或memcpy

9f64e8004a31ddc506e2d101bcb61a04.png

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

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

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

新书介绍

《实战Python设计模式》是作者最近出版的新书,拜托多多关注!

a401be4a132be90e59d3c4b5d2278a1f.png

本书利用Python 的标准GUI 工具包tkinter,通过可执行的示例对23 个设计模式逐个进行说明。这样一方面可以使读者了解真实的软件开发工作中每个设计模式的运用场景和想要解决的问题;另一方面通过对这些问题的解决过程进行说明,让读者明白在编写代码时如何判断使用设计模式的利弊,并合理运用设计模式。

对设计模式感兴趣而且希望随学随用的读者通过本书可以快速跨越从理解到运用的门槛;希望学习Python GUI 编程的读者可以将本书中的示例作为设计和开发的参考;使用Python 语言进行图像分析、数据处理工作的读者可以直接以本书中的示例为基础,迅速构建自己的系统架构。


觉得本文有帮助?请分享给更多人。

关注微信公众号【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值