我还没有看到同时使用 unique_ptr 和 move-semantics 的 pimpl 示例。
我想向 STL 派生容器添加一个 CHelper 类,并使用 pimpl 隐藏 CHelper 的功能。
这看起来对吗?
派生的.h
class CDerived : public set<CSomeSharedPtr>, public CHelper
{
//...
};
`
助手.h
// derived containers need to support both copy and move, so CHelper does too
class CHelper
{
private:
class impl;
unique_ptr<impl> pimpl;
public:
//--- default: need both cotr & cotr (complete class) in order to use unique_ptr<impl>
CHelper();
~CHelper();
//--- copy
CHelper(const CHelper &src); //copy constructor
CHelper& operator=(const CHelper &src);//assignment operator
//--- move
CHelper(CHelper &&src); //move constructor
CHelper& operator=(CHelper &&src);//move operator
//--- expose public methods here
void SetModified(BOOL bSet=TRUE);
};
助手.cpp
//===========================
class CHelper::impl
{
public:
BOOL m_bModified; //has the container been modified (needs to be saved)
// ... other data
impl() {m_bModified = FALSE;}
//--- copy cotr/assign
impl(const impl &src)
{
*this = src;
}
void operator=(const impl &src)
{
m_bModified = src.m_bModified;
// ...other data
}
//--- move cotr/assign ?? do I need to write move cotr/assign ??
};
//============================
CHelper::CHelper() : pimpl(unique_ptr<impl>(new impl())) {}
CHelper::~CHelper() {}
//--- copy
CHelper::CHelper(const CHelper &src)
: pimpl(unique_ptr<impl>(new impl(*src.pimpl))) {}
CHelper& CHelper::operator=(const CHelper &src)
{
if (this != &src)
*pimpl = *src.pimpl;
return *this;
}
//--- move
CHelper::CHelper(CHelper &&src)
{
if (this != &src)
{
pimpl = move(src.pimpl); //use move for unique_ptr
src.pimpl.reset(nullptr);//leave pimpl in defined / destructable state
}
}
CHelper& CHelper::operator=(CHelper &&src)
{
if (this != &src)
{
pimpl = move(src.pimpl); //use 'move' for unique_ptr
src.pimpl.reset(nullptr);//leave pimpl in defined / destructable state
}
return *this;
}