C++: 使用aggregate initialization代替memset來初始化結構體。

在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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容