智能指针的原理都是RAII(Resource Acquisition Is Initialization),即在构造的时候获取资源,在析构的时候释放资源。
为了使用智能指针,需要引入头文件 #include <memory>。
auto_ptr
c++98
解决内存泄漏问题
#include <iostream>
#include <memory>
using namespace std;
class A {
public:
A () {}
~A() {
cout << "Calling A's destructor" << endl;
}
};
class B {
public:
B () {}
~B() {
cout << "Calling B's destructor" << endl;
}
};
int main() {
auto_ptr<A> a(new A());
B *b = new B();
return 0;
}
/**output
Calling A's destructor
*/
解决浅拷贝导致的指针悬挂问题
#include <iostream>
#include <memory>
using namespace std;
class HasPtr
{
public:
HasPtr(char *s);
~HasPtr();
private:
char *ptr;
};
HasPtr::HasPtr(char *s)
{
if (s == nullptr)
{
ptr = new char[1];
*ptr = '\0';
}
else
{
ptr = new char[strlen(s) +1];
strcpy(ptr, s);
}
}
HasPtr::~HasPtr()
{
cout << "destructor ---> " << ptr << endl;
delete ptr;
}
int main()
{
auto_ptr<HasPtr>p1(new HasPtr("Book"));
auto_ptr<HasPtr>p2(p1); // 所有权转移到p2,p1变为empty
return 0;
}
/** Output
destructor ---> Book
*/
需要注意的问题
所有权转移
auto_ptr transfers the ownership when it is assigned to another auto_ptr. This is really an issue while passing the auto_ptr between the functions. Say, I have an auto_ptr in Foo( ) and this pointer is passed another function say Fun( ) from Foo. Now once Fun( ) completes its execution, the ownership is not returned back to Foo.
shared_ptr has the notion called shared ownership. The goal of shared_ptr is very simple: Multiple shared pointers can refer to a single object and when the last shared pointer goes out of scope, memory is released automatically. 从上面这段英文可以看出,shared_ptr是共享所有权的,其内部有一个计数机制。