引入了

智慧指標

可以解決了C++裡的各種資源洩漏問題。但我發現我寫的程式程式碼編譯出來的檔案都較原來的檔案大。

於是我想做一個實驗,看智慧指標會帶來多大的檔案體積開銷。

於是做了個對比實驗:

raw_ptr。cpp

#include

#include

using

namespace

std

class

Child

class

Parent

{

public

~

Parent

();

Child

*

newChild

();

void

hello

()

{

cout

<<

“Parent::Hello”

<<

endl

}

private

vector

<

Child

*>

children_

};

class

Child

{

public

Child

Parent

*

p

parent_

p

{}

void

hello

()

{

cout

<<

“Child::Hello”

<<

endl

parent_

->

hello

();

}

private

Parent

*

parent_

};

Child

*

Parent

::

newChild

()

{

Child

*

child

=

new

Child

this

);

children_

push_back

child

);

return

child

}

Parent

::~

Parent

()

{

for

int

i

=

0

i

<

children_

size

();

++

i

delete

children_

i

];

children_

clear

();

}

int

main

()

{

Parent

p

Child

*

c

=

p

newChild

();

c

->

hello

();

return

0

}

smart_

ptr。cpp

#include

#include

#include

using

namespace

std

class

Child

class

Parent

public

enable_shared_from_this

<

Parent

>

{

public

~

Parent

();

shared_ptr

<

Child

>

newChild

();

void

hello

()

{

cout

<<

“Parent::Hello”

<<

endl

}

private

vector

<

shared_ptr

<

Child

>

>

children_

};

class

Child

{

public

Child

weak_ptr

<

Parent

>

p

parent_

p

{}

void

hello

()

{

cout

<<

“Child::Hello”

<<

endl

shared_ptr

<

Parent

>

sp_parent

=

parent_

lock

();

sp_parent

->

hello

();

}

private

weak_ptr

<

Parent

>

parent_

};

shared_ptr

<

Child

>

Parent

::

newChild

()

{

shared_ptr

<

Child

>

child

=

make_shared

<

Child

>

weak_from_this

());

children_

push_back

child

);

return

child

}

Parent

::~

Parent

()

{

children_

clear

();

}

int

main

()

{

shared_ptr

<

Parent

>

p

=

make_shared

<

Parent

>

();

shared_ptr

<

Child

>

c

=

p

->

newChild

();

c

->

hello

();

return

0

}

empty。cpp

#include

int

main

()

{

std

::

cout

<<

“hello”

<<

std

::

endl

return

0

}

Makefile

all:

g++ -o raw_ptr raw_ptr。cpp -O2

g++ -o smart_

ptr smart_ptr。cpp

-O2

g++ -o empty empty。cpp -O2

strip raw_ptr

strip smart_ptr

strip empty

編譯得到的結果:

C++智慧指標對程式檔案大小的影響

empty 是什麼功能都沒有,編譯它是為了比較出,raw_ptr。cpp 中應用程式程式碼所佔有空間。

將 raw_ptr 與 smart_ptr 都減去 empty 的大小:

raw_ptr 4192B

smart_ptr

8360B

而 smart_ptr 比 raw_ptr 多出 4168B,這多出來的就是使用智慧指標的開銷。

目前來看,智慧指標額外佔用了一倍的程式空間。它們之間的關係是呈倍數增長,還是別的一個關係?

那麼引入智慧指標是哪些地方的開銷呢?

大概有:

類模板 shared_ptr, weak_ptr 為每個型別生成的類。

程式碼邏輯中對智慧指標的操作。

第一項是可預算的,有多少個類,其佔用的空間是可預知的。而第二項,是很不好把控,對

指標物件

訪問越多越佔空間。

mqtt_client

做對比實驗

如下為不使用智慧指標編譯時 -Os -O2,最後 strip 後的結果:

C++智慧指標對程式檔案大小的影響

如果為使用智慧指標編譯後的結果:

C++智慧指標對程式檔案大小的影響

可以看出,多出了:78K,大概多出整體程式碼邏輯的一半。

總結:

使用智慧指標的代價會使程式的體積多出一半。