【1】c++11 智能指针

auto_ptr

unique_ptr

share_ptr

auto_ptr

已弃用,auto_ptr存在内存崩溃的问题,因为采用的是对象所有权模式,

用auto_ptr进行资源转移,不能共享对象的所有权。

#include <iostream>
#include <memory>
#include <string>
using namespace std;

// auto_ptr的所有权独有
int main()
{
        auto_ptr<string> p1(new string("china"));
        auto_ptr<string> p2; 

        // p1赋值给p2, 所有权转交给p2,此时p1不能使用
        p2 = p1; 

        // 访问p1的时候会报错
        cout<<*p2<<endl;
        cout<<*p1<<endl;
}

 

 

unique_ptr

特点:unique_ptr是auto_ptr的优化版本,严格意义上的独享所有权

   同样采用了所有权模式,保证同一时间只能有一个智能指针指向该对象。

因此不允许多个unique_ptr指向同一个对象,所以不允许拷贝与赋值。

#include <iostream>
#include <memory>
#include <string>
#include <stdio.h>
using namespace std;

class Person {
public:
	~Person() {
		cout << "析构person" << endl;
	}
	string str;
};

// 返回值也可以用
unique_ptr<Person> TestFun()
{
	return unique_ptr<Person>(new Person);
}

int main()
{
	// 创建对象p1
	unique_ptr<Person> p1 (new Person);

	// 创建对象p2
	unique_ptr<Person> p2 = TestFun();
	p2->str = "hello world";
	cout << p2->str << endl;

	// 只能有一个对象拥有所有权
	// move
	unique_ptr<Person> p3 = move(p2);

	if (p2) {
		cout << "为真" << endl;
	}
	else {
		cout << "为空" << endl;
	}

	// reset
	p3.reset(new Person);
	
	return 0;
}

  

shared_ptr

  特点:多个指针可以共享相同对象,该对象及资源会在最后一个引用被销毁时释放

  缺点:如果有两个shared_ptr相互引用,那么这两个引用计数永远不为0,资源不被释放

weak_ptr

  特点:解决shared_ptr相互引用时,产生死锁的问题,

做一个优秀的程序媛
原文地址:https://www.cnblogs.com/oytt/p/13627551.html