インテリジェントポインタのカプセル化

2722 ワード

テストコード
#include "stdafx.h"
#include "SmartPt.h"
#include <iostream>
using namespace std;

class A
{
public:
	A(int nVal = 0)
	{
		m_nVal = nVal;
		cout << "A::A()" << endl;
	}

	~A()
	{
		cout << "A::~A()" << endl;
	}

public:
	void Print()
	{
		cout << "A::Print(): value=" << m_nVal << endl;
	}

private:
	int m_nVal;
};

class B
{
public:
	B()
	{
		cout << "B::B()" << endl;
	}

	~B()
	{
		cout << "B::~B()" << endl;
	}

public:
	void Test()
	{
		cout << "B::Test()" << endl;
	}
};

int main()
{
	CSmartPt<A> pa(new A);
	CSmartPt<B> pb(new B);
	CSmartPt<int> pn(new int[100]);

	pa->Print();
	pb->Test();

	for (int i = 0; i < 100; i++)
	{
		pn.Get()[i] = i;
	}

	cout << "Print contents of int arrray.." << endl;
	for (int i = 0; i < 100; i++)
	{
		cout << pn.Get()[i] << "\t";
	}
	cout << endl;

	A* pa1 = new A(123);
	pa.Set(pa1);
	pa->Print();

	A* pa2 = new A(234);
	pa = pa2;

	return 0;
}
 
スマートポインタソース
#pragma once
#include <Windows.h>

template <class T>
class CSmartPt
{
public:
	CSmartPt(T* t)
	{
		m_pData = t;
	}

	~CSmartPt(void)
	{
		Release();
	}

public:
	BOOL Release()
	{
		if (!m_pData)
		{
			return FALSE;
		}

		delete m_pData;
		m_pData = NULL;

		return TRUE;
	}

	T* Get() const
	{
		return m_pData;
	}

	BOOL Set(T* t)
	{
		if (t == m_pData)
		{
			return FALSE;
		}

		Release();

		m_pData = t;

		return TRUE;
	}

public:
	T& operator * () const
	{
		return *m_pData;
	}

	T* operator -> () const
	{
		return m_pData;
	}

	T* operator = (T* t)
	{
		Set(t);
		return m_pData;
	}

	CSmartPt* operator = (CSmartPt* p)
	{
		Set(p->Get());

		return this;
	}
	
private:
    T*	m_pData;
};