1.auto_ptr(虽然可以使用,但该方式已经被c++11摈弃)
#include<iostream> #include<string> #include<memory> using namespace std; //double所在的内存没有机会被释放,将造成内存泄漏 void demo1() { double* pd = new double(); *pd = 25.5; } //ap自带析构函数,声明周期结束时将自动调用析构桉树,释放掉指向的内存 void demo2() { auto_ptr<double> ap(new double); *ap = 25.5; } int main(void) { demo1(); demo2(); cin.get(); return 0; }
shared_ptr 、 unique_ptr 的用法和 auto_ptr用法是一样的:
#include<iostream> #include<string> #include<memory> using namespace std; class Report { private: string str; public: Report(const string s) :str(s) { cout << "Object created." << endl; } ~Report() { cout << "Object deleted." << endl; } void comment() const { cout << str << endl; } }; int main(void) { { auto_ptr<Report> ps(new Report("using auto_ptr")); ps->comment(); } { shared_ptr<Report> ps(new Report("using shared_ptr")); ps->comment(); } { unique_ptr<Report> ps(new Report("using unique_ptr")); ps->comment(); } cin.get(); return 0; }
输出: