C++之智能指针原理与实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ReturningProdigal/article/details/78905719
#include <QCoreApplication>
#include <iostream>
#include <string>
#include <valarray>
#include <stdexcept>
using namespace std;
#define trace(a) cout <<"line:" << __LINE__<< "  func:" << __func__ << "  data:" << a << endl;

class Demo{
public:
    int id;
    Demo(){trace("Demo")}
    Demo(int id){
        trace("Demo")
        this->id = id;
    }
//    Demo(Demo& d){
//        trace("Demo copy");
//        this->id = d.id;
//    }
    ~Demo(){trace("Demo")}
};

class my_shared_ptr{
private:
    Demo *ptr;
public:
    static int refcount;
    my_shared_ptr(){
        trace("my_shared_ptr");
    }
    my_shared_ptr(Demo *d){
        trace("my_shared_ptr");
        this->ptr = d;
        my_shared_ptr::refcount++;
    }
    my_shared_ptr(my_shared_ptr &t){
        trace("my_shared_ptr copy");
        this->ptr = t.ptr;
        my_shared_ptr::refcount++;
    }
    ~my_shared_ptr(){
        trace("my_shared_ptr");
        my_shared_ptr::refcount--;
        if(my_shared_ptr::refcount <= 0){
            delete this->ptr;
        }
    }
    my_shared_ptr& operator =(my_shared_ptr& t){
        trace("my_shared_ptr = ");
        this->ptr = t.ptr;
        my_shared_ptr::refcount++;
    }
};
int my_shared_ptr::refcount = 0;

//my_shared_ptr& test(){
//    my_shared_ptr p(new Demo());
//    //my_shared_ptr q = p;
//    return p;
//}

Demo test(){
    Demo d(2);
    cout << "test d" << endl;
    return d;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

//    my_shared_ptr p = test();//在return时,函数中的局部对象被销毁,则退出函数时将临时变量赋值给新的对象时只是能访问其数据而已

//    cout << "main " << my_shared_ptr::refcount << endl;

    Demo p = test();
    cout << p.id << endl;

    return a.exec();
}

猜你喜欢

转载自blog.csdn.net/ReturningProdigal/article/details/78905719