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();
运行结果:
构建
销毁