/*
* c++进阶
* 智能指针初体验
* 小鱼号的代码日志
*/
#include <QCoreApplication>
#include<iostream>
#include<memory>
using namespace std;
static void interfaceOfSharePrt();
class Object
{
public:
Object(int id):m_id(id)
{
cout << "init obj id" << m_id << endl;
}
~Object()
{
cout << "bye obj" << endl;
}
int getId() const
{
return m_id;
}
private:
int m_id;
};
typedef shared_ptr<Object> ObjectPtr;
void deleterOfObject(Object* obj)
{
if(obj)
{
cout << "delete obj id " << obj->getId() << endl;
}
delete obj;
}
void print(ObjectPtr obj)
{
cout << "print obj count " << obj.use_count()
<< "id "<< obj->getId() << endl;
}e
void printRef(const ObjectPtr& obj)
{
cout << "print obj count " << obj.use_count()
<< "id "<< obj->getId() << endl;
}
void userDelete()
{
ObjectPtr obj(new Object(2),deleterOfObject);
ObjectPtr obj2 = obj;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
interfaceOfSharePrt();
userDelete();
return a.exec();
}
void interfaceOfSharePrt()
{
ObjectPtr nullObj;
cout << "ref count is " << nullObj.use_count() << endl;
ObjectPtr obj(new Object(1));
cout << "ref count is " << obj.use_count() << endl;
ObjectPtr obj2(obj);
cout << "ref count is " << obj.use_count() << endl;
cout << "ref count is " << obj2.use_count() << endl;
ObjectPtr obj3 = obj;
cout << "ref count is " << obj.use_count() << endl;
obj2.reset();
cout << "ref count is " << obj.use_count() << endl;
obj2 = nullptr;
cout << "ref count is " << obj.use_count() << endl;
ObjectPtr obj4;
obj3.swap(obj4);
cout << "ref count is " << obj.use_count() << endl;
swap(obj3,obj4);
cout << "ref count is " << obj.use_count() << endl;
auto p = obj.get();
if(p)
{
cout << "p id is " << p->getId() << endl;
}
if(obj)
{
cout << "obj id is " << obj->getId() << endl;
}
obj4 = nullptr;
cout << "only one hold ptr" << obj.unique() << endl;
print(obj);
printRef(obj);
}
网友评论