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


#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();
}
智能推荐

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告