天天看點

memcpy函數_不要對不能直接拷貝的參數使用memset或memcpySL.con.4: don't use memset or memcpy for arguments that are not trivially-copyableSL.con.4:不要對不能直接拷貝的參數使用memset或memcpy

memcpy函數_不要對不能直接拷貝的參數使用memset或memcpySL.con.4: don't use memset or memcpy for arguments that are not trivially-copyableSL.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成員建議)

原文連結

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#slcon4-dont-use-memset-or-memcpy-for-arguments-that-are-not-trivially-copyable

新書介紹

《實戰Python設計模式》是作者最近出版的新書,拜托多多關注!

memcpy函數_不要對不能直接拷貝的參數使用memset或memcpySL.con.4: don't use memset or memcpy for arguments that are not trivially-copyableSL.con.4:不要對不能直接拷貝的參數使用memset或memcpy

本書利用Python 的标準GUI 工具包tkinter,通過可執行的示例對23 個設計模式逐個進行說明。這樣一方面可以使讀者了解真實的軟體開發工作中每個設計模式的運用場景和想要解決的問題;另一方面通過對這些問題的解決過程進行說明,讓讀者明白在編寫代碼時如何判斷使用設計模式的利弊,并合理運用設計模式。

對設計模式感興趣而且希望随學随用的讀者通過本書可以快速跨越從了解到運用的門檻;希望學習Python GUI 程式設計的讀者可以将本書中的示例作為設計和開發的參考;使用Python 語言進行圖像分析、資料處理工作的讀者可以直接以本書中的示例為基礎,迅速建構自己的系統架構。

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

關注微信公衆号【面向對象思考】輕松學習每一天!

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

繼續閱讀