将 PIMPL 与单例和auto_ptr一起使用

Using PIMPL with singletons and auto_ptr

本文关键字:ptr 一起 auto PIMPL 单例      更新时间:2023-10-16

我有一个包含许多静态方法和实例方法的单例。我想将其导出到 DLL 中,以便我可以在其他地方使用它。但是,这样做会生成编译器警告,因为我没有导出类的私有数据成员。

所以,在我的研究中,我遇到了PIMPL成语,并看到它可以用于做我想做的事情。请让我们避免"单身人士是邪恶/反模式"的争论。就我而言,这是有道理的,因为我的所有子对象都需要一个管理器类。为了简洁起见,我将减少类中的其他一些方法,但我会为一般想法留下足够的内容。

HIDDeviceImpl CPP 文件中空HIDDevice析构函数的想法来自 Ali Çehreli 的这篇文章

HIDDevice.hpp

class HIDDeviceImpl; // Forward Declaration
class HIDDevice
{
public:
    static HIDDevice* getDevice(unsigned short vendorID, unsigned short productID);
    int writeData(const unsigned char *data, int length);

    int readData(unsigned char *data, int length);
    ~HIDDevice(); // Note public destructor declared in HIDDevice.hpp
private:
    std::unique_ptr<HIDDeviceImpl> m_pImpl; // pointer to the implemetation
};

隐藏.cpp

#include "HIDDeviceImpl.hpp"
#include "HIDDevice.hpp"
HIDDevice* HIDDevice::getDevice(unsigned short vendorID, unsigned short productID)
{
    return HIDDeviceImpl::getDevice(vendorID, productID);
}
int HIDDevice::writeData(const unsigned char *data, int length)
{
    return m_pImpl->writeData(data, length);
}

int HIDDevice::readData(unsigned char *data, int length)
{
    return m_pImpl->readData(data, length);
}

HIDDeviceImpl.hpp

#include "HIDDevice.hpp"
class HIDDeviceImpl : public HIDDevice
{
public:
    static HIDDeviceImpl* getDevice(unsigned short vendorID, unsigned short productID);
    int writeData(const unsigned char *data, int length);
    int readData(unsigned char *data, int length);
private:
    // some private static and private member functions and data
    // private constructor and destructor
};

HIDDeviceImpl.hpp

#include "HIDDeviceImpl.hpp"
/** Non-member Static Data Definitions **/
/** internal map used to store all HIDDevice objects */
static std::map<std::string, HIDDeviceImpl*> m_hidDevices;
HIDDeviceImpl* HIDDeviceImpl::getDevice(unsigned short vendorID, unsigned short productID) 
{
    //implementation
}
int HIDDeviceImpl::writeData(const unsigned char *data, int length)
{
    //implementation
}
int HIDDeviceImpl::readData(unsigned char *data, int length)
{
    //implementation
}
HIDDeviceImpl::HIDDeviceImpl(unsigned short vendorID, unsigned short productID, std::string serialNumber)
{
    // implementation
}
HIDDeviceImpl::~HIDDeviceImpl()
{
    // implementation
}
// Note the HIDDevice destructor is declared in the HIDDeviceImpl file.
HIDDevice::~HIDDevice()
{
    // intentionally left blank
}

现在,生成的错误如下:

error C2248: 'HIDDeviceImpl::~HIDDeviceImpl' : cannot access private member declared in class 'HIDDeviceImpl'

这源于HIDDevice.hpp中的auto_ptr

为什么不只执行错误消息告诉您要做的事情,并使析构函数公开? 这样,std::unique_ptr的内部就可以访问它。