自实现智能指针Shared_ptr
// MySharedPtr.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <windows.h>
#include <future>
#include <iostream>
using namespace std;
class SharedPtrTest
{
public:
SharedPtrTest();
~SharedPtrTest();
void testFunc();
};
SharedPtrTest::SharedPtrTest()
{
}
SharedPtrTest::~SharedPtrTest()
{
MessageBoxA(NULL, __FUNCTION__, "", 0);
}
void SharedPtrTest::testFunc()
{
MessageBoxA(NULL, __FUNCTION__, "", 0);
}
void testFunc_1()
{
shared_ptr<SharedPtrTest> p1(new SharedPtrTest);
MessageBoxA(NULL, __FUNCTION__, "", 0);
}
shared_ptr<SharedPtrTest> testFunc_2()
{
shared_ptr<SharedPtrTest> p1(new SharedPtrTest);
MessageBoxA(NULL, __FUNCTION__, "", 0);
return p1;
}
template <typename T>
class MySharedPtr
{
public:
MySharedPtr(T * p) :_count(new int(1)), _object(p){}
MySharedPtr(MySharedPtr<T> & other) :_count(&(++(*other._count))), _object(other._object){}
T * operator->()
{
return _object;
}
T & operator*()
{
return *_object;
}
MySharedPtr<T> & operator = (MySharedPtr<T> & other)
{
++*other.count;
if (this == &other)
return *this;
if (this->_object != nullptr&&(--*(this->_count)))
{
delete _count;
delete _object;
}
this->_count = other._count;
this->_object = other._object;
return *this;
}
~MySharedPtr()
{
if (--*this->_count == 0)
{
delete _count;
delete _object;
}
}
int getRefCount(){ return this->_count; }
private:
int * _count;
T * _object;
};
MySharedPtr<SharedPtrTest> testFunc_3()
{
MySharedPtr<SharedPtrTest> p1(new SharedPtrTest);
MessageBoxA(NULL, __FUNCTION__, "", 0);
return p1;
}
/*
避免循环引用。智能指针最大的一个陷阱是循环引用,循环引用会导致内存泄漏。解决方法是AStruct或BStruct改为weak_ptr。
禁止通过shared_from_this()返回this指针,这样做可能也会造成二次析构
要在函数实参中创建shared_ptr。因为C++的函数参数的计算顺序在不同的编译器下是不同的。正确的做法是先创建好,然后再传入。
*/
int _tmain(int argc, _TCHAR* argv[])
{
//shared_ptr 使用测试
/*shared_ptr<SharedPtrTest> p2 = testFunc_2();
p2->testFunc();
*/
//MySharedPtr 使用测试
//MySharedPtr<SharedPtrTest> p(new SharedPtrTest);
//p->testFunc();
//testFunc_1();
MySharedPtr<SharedPtrTest> p2 = testFunc_3();
MessageBoxA(NULL, __FUNCTION__, "", 0);
return 0;
}
浙公网安备 33010602011771号