2018年1月28日 星期日

C++ 能否用 memcpy 複製 class / struct 的資料?

答案是: POD (plain old data) type 可以。POD type 可和 C 互通, CPP Reference POD Type 的介紹:

Specifies that the type is POD (Plain Old Data) type. This means the type is compatible with the types used in the C programming language, can be manipulated using C library functions: it can be created with std::malloc, it can be copied with std::memmove, etc, and can be exchanged with C libraries directly, in its binary form.

C++11 開始可用 std::is_pod 判斷

在看 POD 定義的過程發現 Standard layout type 的定義也重要的:

Specifies that a type is standard layout type. Standard layout types are useful for communicating with code written in other programming languages.

符合 standard layout type 才能用 reinterpret_cast 轉型成第一個 member 的 type

不過最穩的最法是直接用 C++11 提供的 std::is_trivially_copyable 判斷, 成立的話就可以安心地用 memcpy。

如何讓 C++ STL, smart pointer 和 forward declaration

有時在 class 內訂義 member 用 std::vector 或 std::unique_ptr, 可以用 forward declaration 宣告 MyObject, 有時不行。原因在於是否有觸發 compiler inline vector / unique_ptr 的 ctor / dtor。

所以避免造成 inline ctor / dtor, 就可以用 forward declaration 宣告 MyObject, 降低程式之間不必要的 dependency, 減少重新編譯時間。

參考資料:

在 Fedora 下裝 id-utils

Fedora 似乎因為執行檔撞名,而沒有提供 id-utils 的套件 ,但這是使用 gj 的必要套件,只好自己編。從官網抓好 tarball ,解開來編譯 (./configure && make)就是了。 但編譯後會遇到錯誤: ./stdio.h:10...