1、auto_ptr不能共享所有权。
2、auto_ptr不能指向数组
3、auto_ptr不能作为容器的成员。
4、不能通过赋值操作来初始化auto_ptr
std::auto_ptr<int> p(new int(42)); //OK
std::auto_ptr<int> p = new int(42); //ERROR
这是因为auto_ptr 的构造函数被定义为了explicit
2、auto_ptr不能指向数组
3、auto_ptr不能作为容器的成员。
4、不能通过赋值操作来初始化auto_ptr
std::auto_ptr<int> p(new int(42)); //OK
std::auto_ptr<int> p = new int(42); //ERROR
这是因为auto_ptr 的构造函数被定义为了explicit
5、不要把auto_ptr放入容器,因为容器是把你放入容器的元素做了一个副本拷贝,而auto_ptr又不能共享所有权,
所以会使原来的auto_ptr指向的对象失效;
另外,auto_ptr只能指针的release函数只是让出对象内存所有权,不会调用对象的析构函数,例如如下代码:
void TestAutoPtr3()
{
std::auto_ptr<Simple> my_memory(new Simple(1));
if (my_memory.get())
{
my_memory.release();
}
}
执行结果为:
Simple: 1
看到什么异常了吗?我们创建出来的对象没有被析构,没有输出“~Simple: 1”,导致内存泄露。当我们不想让 my_memory 继续生存下去,我们调用 release() 函数释放内存,结果却导致内存泄露
正确的代码应该为:
void TestAutoPtr3()
{
std::auto_ptr<Simple> my_memory(new Simple(1));
if (my_memory.get())
{
Simple* temp_memory = my_memory.release();
delete temp_memory;
}
}
或
void TestAutoPtr3()
{
std::auto_ptr<Simple> my_memory(new Simple(1));
if (my_memory.get())
{
my_memory.reset(); // 释放 my_memory 内部管理的内存
}
}
5种针对auto_ptr不足的指针如下:需要详细了解可以去查看相当文档,与测试新代码。
1. shared_ptr是Boost库所提供的一个智能指针的实现,shared_ptr就是为了解决auto_ptr在对象所有权上的局限性(auto_ptr是独占的),在使用引用计数的机制上提供了可以共享所有权的智能指针.
2. shared_ptr比auto_ptr更安全
3. shared_ptr是可以拷贝和赋值的,拷贝行为也是等价的,并且可以被比较,这意味这它可被放入标准库的一般容器(vector,list)和关联容器中(map)。
scoped_ptr | <boost/scoped_ptr.hpp> | 简单的单一对象的唯一所有权。不可拷贝。 |
scoped_array | <boost/scoped_array.hpp> | 简单的数组的唯一所有权。不可拷贝。 |
shared_ptr | <boost/shared_ptr.hpp> | 在多个指针间共享的对象所有权。 |
shared_array | <boost/shared_array.hpp> | 在多个指针间共享的数组所有权。 |
weak_ptr | <boost/weak_ptr.hpp> | 一个属于 shared_ptr 的对象的无所有权的观察者。 |
intrusive_ptr | <boost/intrusive_ptr.hpp> | 带有一个侵入式引用计数的对象的共享所有权。 |
1. shared_ptr是Boost库所提供的一个智能指针的实现,shared_ptr就是为了解决auto_ptr在对象所有权上的局限性(auto_ptr是独占的),在使用引用计数的机制上提供了可以共享所有权的智能指针.
2. shared_ptr比auto_ptr更安全
3. shared_ptr是可以拷贝和赋值的,拷贝行为也是等价的,并且可以被比较,这意味这它可被放入标准库的一般容器(vector,list)和关联容器中(map)。