1 析构函数声明为私有, 有些资源必须要在析构前释放掉,则将析构函数声明为私有,然后另外再定义一个公有的destroy函数,先做释放资源操作,再调用析构函数。 delete this.
2 当类成员中有文件描述符,锁之类的系统资源时,因为这些资源不具备可复制性。所以要防止使用者复制使用它们。此时的做法是将copy构造函数、赋值操作符声明为private
3 析构函数声明为私有,则在创建该类的对象时必须是在堆上创建,如果是在栈上创建会导致编译不过。原因:编译器可见性,在栈上创建对象时必须是析构函数可见,而声明为private则不可见。
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
using namespace std;
template<typename T>
class DeviceManager {
public:
DeviceManager(const T a, string filePath) : m_deviceNumber(a), m_filePath(filePath) {
}
void CreateDevice() {
m_file = fopen(m_filePath.c_str(), "w");
}
void DestroyDevice() {
if (m_file != nullptr) {
cout << "clean the resource" << endl;
fclose(m_file);
m_file = nullptr;
}
delete this;
}
private:
// private destructure.
virtual ~DeviceManager() {
cout << "~DeviceManager()" << endl;
}
// private assignment.
DeviceManager& operator=(const DeviceManager& deviceManager)
{
if (&deviceManager != this) {
m_deviceNumber = deviceManager.m_deviceNumber;
m_file = deviceManager.m_file;
m_filePath = deviceManager.m_filePath;
}
return *this;
}
// private copy constructure.
DeviceManager(const DeviceManager& deviceManager)
{
cout << "copy constructure" << endl;
m_deviceNumber = deviceManager.m_deviceNumber;
m_file = deviceManager.m_file;
m_filePath = deviceManager.m_filePath;
}
private:
string m_filePath;
T m_deviceNumber;
FILE *m_file;
};
int main()
{
string deviceNumber = "ssd";
//DeviceManager<string> deviceManager(deviceNumber, "~/my_project");
DeviceManager<string> *p = new DeviceManager<string>(deviceNumber, "~/my_project/aa.log");
p->CreateDevice();
p->DestroyDevice();
return 0;
}