智能指针解决了程序员忘记释放对象,导致内存遗漏的问题
如下:
#include <iostream>
#include <memory>
#include <unistd.h>
using namespace std;
class A18 {
public:
A18() {
cout << "default constructor" << endl;
}
int say() {
cout << "A say:" << endl;
return 0;
}
~A18() {
cout << "Destructor called" << endl;
}
};
void f0() {
A18 *a=new A18();
a->say();
}
int main() {
f0();
sleep(2);
cout << "end" << endl;
return 0;
}
我们在f0()方法中new了一个A18的对象,但是忘记释放。
主程序在调用f0之后2秒退出,控制台打印如下:
default constructor
A say:
end
可以发现没有调用A18的析构函数,发生了内存泄露。
接下来我们使用
#include <iostream>
#include <memory>
#include <unistd.h>
using namespace std;
class A18 {
public:
A18() {
cout << "default constructor" << endl;
}
int say() {
cout << "A say:" << endl;
return 0;
}
~A18() {
cout << "Destructor called" << endl;
}
};
void f0() {
unique_ptr<A18> a(new A18());
a->say();
}
int main() {
f0();
sleep(2);
cout << "end" << endl;
return 0;
}
编译: g++ a.cpp -o a
运行 : ./a
继续运行看打印结果:
default constructor
A say:
Destructor called
end
完美,A18析构函数被调用,说明对象被释放。