C++: 使用aggregate initialization代替memset來初始化結(jié)構(gòu)體。

在C里面經(jīng)常使用memset來把一個(gè)結(jié)構(gòu)體的內(nèi)容全部設(shè)置為0。

memset(ps, 0, sizeof(S));

在C++11里面,利用aggregate initialization特性,可以寫的更加好看。

void foo(S *ps){
    *ps = { 0 }; // use aggregate initialization
}

*ps = { 0 };實(shí)際發(fā)生的事情是ps->operator=({ 0 });。在沒有優(yōu)化的情況下,{ 0 }實(shí)際上構(gòu)造了一個(gè)struct S的臨時(shí)對象,然后傳給了opeator=這個(gè)函數(shù)。

PS:*ps = { 0 };memset的行為還是有一定區(qū)別的。如果struct S里面有padding的數(shù)據(jù)的話,那么memset也會把padding的數(shù)據(jù)也設(shè)置成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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容