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

网友投稿 268 2022-12-02

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

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成员建议)

原文链接

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

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

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

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

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Java SpringBoot 使用拦截器作为权限控制的实现方法
下一篇:C++核心准则​NR.1:不要坚持所有声明都应该放在函数顶部
相关文章

 发表评论

暂时没有评论,来抢沙发吧~