将PIMPL用于单例和auto_ptr

时间:2016-07-15 15:00:26

标签: c++ inheritance pimpl-idiom

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

所以,在我的研究中,我遇到了PIMPL习语,并发现它可以用来做我想做的事情。请让我们避免“单身人士是邪恶/反模式”的论点。在我的情况下它是有道理的,因为我需要一个所有子对象的经理类。为了简洁起见,我将减少课堂上的其他一些方法,但我会留下足够的想法。

HIDDevice CPP文件中空HIDDeviceImpl析构函数的想法来自AliÇehreli的this article

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

HIDDevice.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

1 个答案:

答案 0 :(得分:1)

为什么不执行错误消息告诉您的操作,并将析构函数公开?这样,std::unique_ptr的内部可以访问它。