shared_ptr是C++11中最智能的指针,它使用引用计数,当使用一个shared_ptr构造或赋值给另外一个shared_ptr时,
引用计数+1.当一个shared_ptr销毁时引用计数-1,直到引用计数为0时,delete掉申请的资源。
问题:
1.关于shared_ptr()构造:shared_ptr<int> ipNull();这里的ipNUll会被解释为function,不可以作为左值
使用。如果要声明一个原始指针为null且引用计数为0的shared_ptr应该使用:shared_ptr<int> ipNull;
2.shared_ptr不可交叉引用,若要交叉引用,则应该使用weak_ptr
—————————————————————————
shared_ptr的简单使用
#include <iostream>
#include <memory>
#include <cstdio>
using namespace std;
int main()
{
//*<constructor:>*//
shared_ptr<int> sipnull(); //create a shared_ptr,but it manager a nullptr and it's reference-count is zero
shared_ptr<int> sip(new int(13)); //create a new obj,it's reference-count is one
shared_ptr<int> sip1(sip); //cause reference-count increase to two
sipnull.reset(new int(12)); //ERROR:".reset"的左边必须有类/结构/联合...
//sipnull = sip; //ERROR:C2659,此错误是编译器将左边变量类型解释为函数造成的
//正确的用法是:shared_ptr<int> sipnull;
cout << "sip and sip1 reference-count is:"
<< sip.use_count() << endl; //cout :"sip and sip1 reference-count is:2"
cout << "sip & sip1 is not null?" << boolalpha << sip.operator bool() << endl;
//"sip & sip1 is not null?true"