天天看點

5.Boost之“資源申請即初始化” RAII



1.raii:資源申請即初始化:

#define

_crt_secure_no_warnings

#include

<iostream>

<stdlib.h>

<string>

using

namespace

std;

class

mystr

{

public:

char *p

= nullptr;

mystr(const

char *str)

cout <<

"建構"

<< endl;

int

length =

strlen(str);

p =

new

char[length

+ 1];

strcpy(p,

str);

p[length]

= '\0';

}

~mystr()

"銷毀"

delete[]

p;

};

void

go()

= new

char[100];

//raii避免記憶體洩露,一般情況下,堆上的記憶體當作棧上來使用

//棧記憶體有限,希望自動釋放,用很大的記憶體。

str1 =

"abcd";

main()

go();

cin.get();

運作結果:

建構

銷毀

上一篇: 7.Boost之thread
下一篇: 4.Boost之ref