日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

基类数组存放派生类_永远不要将派生类数组赋值给基类类型指针

發布時間:2023/12/2 编程问答 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 基类数组存放派生类_永远不要将派生类数组赋值给基类类型指针 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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].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.
  • 提示所有數組退化和基類類型向派生類類型轉換的情況。
  • 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


覺得本文有幫助?請分享給更多人。

更多精彩文章歡迎關注微信公眾號【面向對象思考】!

面向對象開發,面向對象思考!

總結

以上是生活随笔為你收集整理的基类数组存放派生类_永远不要将派生类数组赋值给基类类型指针的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。