I learn pimpl in effective modern cpp,after do some search,no one has talk about the pimpl idiom's impl class's destructor implement, is it unnecessary?
//in widget.h
#include <memory>
class Widget{
public:
Widget();
private:
struct Impl;
std::unique_ptr<Impl> pImpl;
};
//in widget.cpp
........
struct Widget::Impl{
std::string name; // Widget::Impl
std::vector<double> data;
};
struct Widget::~Impl() //error!!!,how can we implement it
{
};
The PIMPL idiom's implementation interface structure cannot be declared as a private
field of a class. Also, the declaration of a unique_ptr
to an incomplete datatype is not allowed in C++ so we have to opt for plain old pointers to declare the PIMPL and manually new
and delete
it appropriately.
The destructor of the struct Impl
can be defined like this in widget.cpp
:
Widget::Impl::~Impl()
{
};
The final code may look something like this:
class Widget
{
public:
Widget();
~Widget();
struct Impl;
private:
Impl* pImpl;
};
struct Widget::Impl
{
Impl();
std::string name; // Widget::Impl
std::vector<double> data;
~Impl();
};
//Widget Impl Constructor
Widget::Impl::Impl()
{
}
//Widget Impl Destructor
Widget::Impl::~Impl()
{
};
//Widget Constructor
Widget::Widget() : pImpl(nullptr)
{
pImpl = new Impl();
}
//Widget Destructor
Widget::~Widget()
{
delete pImpl;
pImpl = nullptr;
}
thanks for demo code post by @Retired Ninja,it helps a lot,the point is,we need a declaration of ~Impl in the cpp file:
Widget::Widget():pImpl(std::make_unique<Impl>())
{
}
struct Widget::Impl {
std::string name;
std::vector<double> data;
~Impl();// need this !!
};
Widget::Impl::~Impl(){
};
Widget::~Widget() {
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.