0
点赞
收藏
分享

微信扫一扫

c++ 智能指针 shared_ptr 的使用

一只1994 2022-01-31 阅读 75

注意 编译的时候要指定 --std=c++11
例如

g++ myshareptr.cpp --std=c++11

代码示例

#include<iostream>
#include<string>
#include<memory>

using namespace std;

class Report
{
   private:
          string str;
   public:
          Report(const std::string s) :str(s)
          {
                   cout<<"Object created\n";
          }
          ~Report()
          {
                 cout<<"Object deleted\n";
	  }
          void comment() const
          {
		cout<<str<<"**************\n";
          }
          
};

int main()
{
  
   //shared_ptr<Report> ps(new Report("using share_ptr"));
   Report *pa = new Report("using share_ptr");
   shared_ptr<Report> ps(pa);
   cout<<"count():  \n"<<ps.use_count()<<endl;
   ps->comment();  //注意 通过 -> 调用管理指针的函数
   ps.reset();
   cout<<"count():  \n"<<ps.use_count()<<endl;
   return 0;
}
举报

相关推荐

0 条评论