在C里面經常使用memset來把一個結構體的內容全部設置為0。
memset(ps, 0, sizeof(S));
在C++11里面,利用aggregate initialization特性,可以寫的更加好看。
void foo(S *ps){
*ps = { 0 }; // use aggregate initialization
}
*ps = { 0 };
實際發生的事情是ps->operator=({ 0 });
。在沒有優化的情況下,{ 0 }
實際上構造了一個struct S
的臨時對象,然后傳給了opeator=
這個函數。
PS:*ps = { 0 };
和memset
的行為還是有一定區別的。如果struct S
里面有padding的數據的話,那么memset也會把padding的數據也設置成0,而*ps = { 0 };
不會。
測試代碼(ideone)
#include <string.h>
#include <iostream>
using namespace std;
struct S {
int x;
//private:
S& operator=(const S& other){
cout << "Address of this " << this << endl;
cout << "Address of other " << &other << endl;
return *this;
};
};
void foo(S *ps){
memset(ps, 0, sizeof(S)); // old C way
*ps = { 0 }; // use aggregate initialization
}
int main(void)
{
S s = { 2 };
foo(&s);
return 0;
}
VS2013下輸出是
Address of this 0046FA84
Address of other 0046F8E0