智能指针,大爱啊

/*
智能指针:
auto_ptr 定义在memory模块里&&std命名空间里
一旦执行对象的指针,生存期结束,就会释放自己所指向的对象
*/

#include <cassert>
#include <cstdio> //cstdio即 C语言的stdio.h
#include <memory>
using namespace std;

class X{
public:
    X(){printf("X!
");}
    ~X(){printf("~X
");}
    virtual void say(){printf("hello!
");}
};

class Y : public X{
public:
    void say(){printf("say hello in claa Y! 
");}
};

void test_define_aptr(){
    std::auto_ptr<X> ap (new X());
    assert(ap.get()!=NULL);
    ap->say();

}

void say(std::auto_ptr<X> *ap){
    (*ap)->say();
}

void test_pass_aptr(){
    X *p = new Y();
    auto_ptr<X> ap (p);
    assert(ap.get()!=NULL);
    say(&ap);
}

int main(){
    test_define_aptr();
    test_pass_aptr();
}
原文地址:https://www.cnblogs.com/code-style/p/3361188.html