谈谈为何需要将类的成员函数声明为private

26 篇文章 0 订阅

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值