注意 编译的时候要指定 --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;
}