基类数组存放派生类_永远不要将派生类数组赋值给基类类型指针
生活随笔
收集整理的這篇文章主要介紹了
基类数组存放派生类_永远不要将派生类数组赋值给基类类型指针
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
C.152: Never assign a pointer to an array of derived class objects to a pointer to its base
C.152:永遠(yuǎn)不要將派生類數(shù)組的指針賦值給基類指針
Reason(原因)
Subscripting the resulting base pointer will lead to invalid object access and probably to memory corruption.
作為賦值結(jié)果的基類指針的下標(biāo)運算會引起無效的對象訪問并可能發(fā)生內(nèi)存破壞。
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].yuse(a); // bad: a decays to &a[0] which is converted to a B*Enforcement(實施建議)
- Flag all combinations of array decay and base to derived conversions.
- 提示所有數(shù)組退化和基類類型向派生類類型轉(zhuǎn)換的情況。
- 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傳遞數(shù)組而不是指針,也不要再放入span之前讓數(shù)組名經(jīng)過一次派生類向基類類型的轉(zhuǎn)換。
原文鏈接:
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c151-use-make_shared-to-construct-objects-owned-by-shared_ptrs
覺得本文有幫助?請分享給更多人。
更多精彩文章歡迎關(guān)注微信公眾號【面向?qū)ο笏伎肌?#xff01;
面向?qū)ο箝_發(fā),面向?qū)ο笏伎?#xff01;
總結(jié)
以上是生活随笔為你收集整理的基类数组存放派生类_永远不要将派生类数组赋值给基类类型指针的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python我想对你说_python学习
- 下一篇: spring中的设计模式_面试:设计模式