技术宅,fat-man

增加语言的了解程度可以避免写出愚蠢的代码

导航

智能指针,大爱啊

 

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

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

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

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

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();
}

 

posted on 2013-10-10 14:09  codestyle  阅读(202)  评论(0)    收藏  举报