智能指针 Smart Pointer
用来改善传统指针的问题
-
需要手动管理内存
-
容易发生内存泄露(忘记释放、出现异常等)
比如:
一旦test()抛出异常,p指针的内存就不会被释放,发生内存泄露。 -
释放后产生野指针
智能指针就是为了解决传统指针存在的问题
- auto_prt:属于C++98标准,在C++11已不推荐使用(有缺陷,比如不能用于数组
- shared_ptr:属于C++11标准
- unique_ptr:属于C++11标准
auto_ptr
class Person {
int m_age;
public:
Person() {
cout << "Person()" << endl;
}
Person(int age): m_age(age) {
cout << "Person(int)" << endl;
}
~Person() {
cout << "~Person()" << endl;
}
void run() {
cout << "run()" << endl;
}
};
void test() {
// 可以理解为:智能指针p指向了堆空间的Person对象
auto_ptr<Person> p(new Person(20));
p->run();
}
int main() {
test();
getchar();
return 0;
}
// 输出:
// Person(int)
// run()
// ~Person()
// 并没有调用析构函数,但会自动调用
智能指针不能指向栈空间的对象!因为智能指针是堆空间指针,析构时会double free!<