1,代理指针,保证对象的释放
// ProxyPtr.cpp
#include "stdafx.h"
#include <iostream>
using namespace std;
class Complex
{
private:
double m_f64Real;
double m_f64Image;
public:
Complex(double f64Real = 0.0, double f64Image = 0.0)
{
cout << "in Complex" << endl;
m_f64Real = f64Real;
m_f64Image = f64Image;
}
virtual ~Complex()
{
cout << "in ~Complex" << endl;
}
void Display()
{
cout << "(" << m_f64Real << ", " << m_f64Image << ")" << endl;
}
};
class ComplexPtr
{
private:
Complex* m_poComplex;
public:
explicit ComplexPtr(Complex* poComplex) : m_poComplex(poComplex)
{
cout << "in ComplexPtr" << endl;
}
virtual ~ComplexPtr() // 退栈时自动调用析构函数
{
cout << "in ~ComplexPtr" << endl;
if (m_poComplex)
{
delete m_poComplex;
m_poComplex = NULL;
}
}
Complex* operator ->()
{
return m_poComplex;
}
Complex& operator *()
{
return *m_poComplex;
}
private:
ComplexPtr(const ComplexPtr&);
ComplexPtr& operator =(const ComplexPtr&);
void* operator new(size_t); // 声明为私有的,使得不能在堆上分配ComplexPtr类型的对象
//void operator delete(void*);
void* operator new[](size_t); // 声明为私有的,使得不能在堆上分配ComplexPtr类型的对象
//void operator delete[](void*);
};
int main()
{
ComplexPtr oComplexPtr(new Complex(10, 10));
oComplexPtr->Display();
(*oComplexPtr).Display();
//ComplexPtr* poComplexPtr = new ComplexPtr(new Complex(20, 20)); // 编译出错,因为new声明为私有的了
return 0;
}
2,非公有的构造函数,使得在类域之外无论是在栈上还是在堆上均不能创建对象
// NonePublicConstructor.cpp
#include "stdafx.h"
#include <iostream>
using namespace std;
class Test
{
protected: // 非公有的构造函数,使得在类域之外无论是在栈上还是在堆上均不能创建对象
Test()
{
cout << "in Test" << endl;
}
public:
virtual ~Test()
{
cout << "in ~Test" << endl;
}
static Test* CreateInstance() // 相当于一个工厂方法,也可使用单件那样的方式,在类中保存一个对象
{
return new Test(); // 在类域之类,可以访问非公有的构造函数
}
};
int main()
{
//Test t; // 编译报错
//Test* pt = new Test(); // 编译报错
Test* pt = Test::CreateInstance();
delete pt;
return 0;
}
3,非公有的析构函数,使得在不能在栈上创建对象,因为退栈时会自动调用析构函数,即只能在堆上创建对象
// NonePublicDestructor.cpp
#include "stdafx.h"
#include <iostream>
using namespace std;
class Test
{
public:
Test()
{
cout << "in Test" << endl;
}
void Release()
{
cout << "in Release" << endl;
delete this; // 此处自动调用析构函数,因为是在类域中调用,所以可以访问私有的析构函数
}
private: // 私有的析构函数,使得在不能在栈上创建对象,因为退栈时会自动调用析构函数,即只能在堆上创建对象
~Test()
{
cout << "in ~Test" << endl;
}
};
int main()
{
//Test t; // 编译报错
Test* pt = new Test();
pt->Release();
return 0;
}
4,只能在栈上创建,不能在堆上创建:
将new和delete重载为私有的。