问题起源
实现Pimpl时,使用unique_ptr时,编译会报如下错误:
[build] /usr/include/c++/9/bits/unique_ptr.h: In instantiation of ‘void std::default_delete<_Tp>::operator()(_Tp*) const [with _Tp = widget::impl]’:
[build] /usr/include/c++/9/bits/unique_ptr.h:292:17: required from ‘std::unique_ptr<_Tp, _Dp>::~unique_ptr() [with _Tp = widget::impl; _Dp = std::default_deletewidget::impl]’
[build] /usr/include/c++/9/experimental/propagate_const:63:11: required from here
[build] /usr/include/c++/9/bits/unique_ptr.h:79:16: error: invalid application of ‘sizeof’ to incomplete type ‘widget::impl’
[build] 79 | static_assert(sizeof(_Tp)>0,
[build] | ^~~~~~~~~~~
样例代码:
#include <iostream>
#include <memory>
#include <experimental/propagate_const>
// interface (widget.h)
class widget {
class impl;
std::experimental::propagate_const<std::unique_ptr<impl>> pImpl;
public:
void draw();
bool shown() const {
return true; } // public API that implementation has to call
widget(int);
widget(widget&&); // defined in the implementation file
// Note: calling draw() on moved-from object is UB
widget(const widget&) = delete;
widget&