欢迎大家来到IT世界,在知识的湖畔探索吧!
C.152: Never assign a pointer to an array of derived class objects to a pointer to its base
C.152:永远不要将派生类数组的指针赋值给基类指针
Reason(原因)
Subscripting the resulting base pointer will lead to invalid object access and probably to memory corruption.
作为赋值结果的基类指针的下标运算会引起无效的对象访问并可能发生内存破坏。
Example(示例)
struct B { int x; };
struct D : B { int y; };
void use(B*);
D a[] = {{1, 2}, {3, 4}, {5, 6}};
B* p = a; // bad: a decays to &a[0] which is converted to a B*
p[1].x = 7; // overwrite D[0].y
use(a); // bad: a decays to &a[0] which is converted to a B*
欢迎大家来到IT世界,在知识的湖畔探索吧!
Enforcement(实施建议)
- Flag all combinations of array decay and base to derived conversions.
- 提示所有数组退化和基类类型向派生类类型转换的情况。
- Pass an array as a span rather than as a pointer, and don’t let the array name suffer a derived-to-base conversion before getting into the span
- 使用span传递数组而不是指针,也不要再放入span之前让数组名经过一次派生类向基类类型的转换。
原文链接:
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c151-use-make_shared-to-construct-objects-owned-by-shared_ptrs
觉得本文有帮助?请分享给更多人。
更多精彩文章欢迎关注微信公众号【面向对象思考】!
面向对象开发,面向对象思考!
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://itzsg.com/34723.html