0

我在有效的现代cpp中学习pimpl,经过一番搜索,没有人谈论pimpl成语的impl类的析构函数,是不是没有必要?

//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
{
};
4

2 回答 2

0

感谢@Retired Ninja 发布的演示代码,它有很大帮助,关键是,我们需要在 cpp 文件中声明 ~Impl:

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() {
 }
于 2017-06-07T09:26:44.960 回答
0

PIMPL 成语的实现接口结构不能声明为private类的字段。此外,unique_ptr在 C++ 中不允许将 a 声明为不完整的数据类型,因此我们必须选择普通的旧指针来声明 PIMPL,newdelete适当地手动声明它。

的析构函数struct Impl可以这样定义widget.cpp

Widget::Impl::~Impl()
{

};

最终代码可能如下所示:

小部件.h

class Widget
{
public:
    Widget();
    ~Widget();
    struct Impl;
private:
    Impl* pImpl;
};

小部件.cpp

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;
}
于 2017-06-07T04:09:43.780 回答