還好,上面的鏈接可以找到我們所需要的答案。不過如果說缺省的拷貝構造函數是member-wise的方式,估計大家不直觀,至少我在這方面就把它和bitwise的方式混淆了。
還好,搜索到另外一篇blog,可以讓我們很直觀的來體會member-wise了。
1
2
3
4
5
|
class MyClass {
int x;
char c;
std::string s;
};
|
the compiler-provided copy constructor is exactly equivalent to:
1
2
3
|
MyClass::MyClass( const MyClass& other ) :
x( other.x ), c( other.c ), s( other.s )
{}
|
MyClass& MyClass::operator=( const MyClass& rhs ) {
x = other.x;
c = other.c;
s = other.s;
return *this;
}
|
看到了嗎? 所謂的member-wise就是編譯器逐個的成員進行賦值操作,而不是等同於bitwise(也就是memcpy).
the difference between member-wise copying and bitwise copying (such as a memcpy()call) is significant in two cases:
- copying of subobjects
- copying of padding bytes
也就是第一篇文章中介紹的,我把上面的翻譯一下:
成員方式的拷貝(member-wise copying)和位方式的拷貝(bitwise copying,也就是通過memcpy之類來實現的拷貝)主要差別在於兩方面:
1. 子對象的拷貝
2. padding字節的拷貝
位方式拷貝,是把整個內存的內容都拷貝過去,這在有子對象的情況下是個災難。估計大家都知道。
但有時發現自己沒有子對象,只是簡單的數值類型時,一定要主要padding的字節,儘量不要通過memcmp來比較兩個對象的類容是否相等。要通過member-wise的方式,逐個成員數據進行比較 (切記)。
終於把這塊短板不起來了,呵呵。
後記,爲了進一步鞏固先前的模糊的部分,貼上另外一個blog。 關於什麼是POD的類型?
POD主要是用於和C代碼來打交道的。什麼是POD結構(Plain Old Data)? http://www.fnal.gov/docs/working-groups/fpcltf/Pkg/ISOcxx/doc/POD.html
expression |
POD type T |
non-POD type T |
new T |
not initialized |
default-initialized |
new T() |
always default-initialized |
new T(x) |
always initialized via a constructor |