我正在学习STFT课程.在标题中编译就好了:
class STFT; // pimpl off to prevent point name clash class Whatever { private: STFT* stft;
这在实施中:
#include "STFT.h" Whatever::Whatever() : stft(new STFT()) { // blah blah } Whatever::~Whatever() { delete stft; // pure evil }
但是,切换到std :: unique_ptr< STFT> STFT;在标题中的原始指针,并删除析构函数,我得到
error: invalid application of ‘sizeof’ to an incomplete type ‘STFT’
static_assert(sizeof(_Tp) > 0,“default_delete can not delete incomplete type”);
但是如果我只提供一个空的析构函数Whatever :: ~Whatever(){},那么它编译得很好.这让我完全难过.请填写我这个毫无意义的析构函数为我做的事情.
解决方法
std::unique_ptr may be constructed for an incomplete type T,such as
to facilitate the use as a handle in the Pimpl idiom. If the default
deleter is used,T must be complete at the point in code where the
deleter is invoked,which happens in the destructor,move assignment
operator,and reset member function of std::unique_ptr. (Conversely,
std::shared_ptr can’t be constructed from a raw pointer to incomplete
type,but can be destroyed where T is incomplete).
我们可以在下面的代码中看到:
#include <memory> class STFT; // pimpl off to prevent point name clash class Whatever { public: ~Whatever() ; private: std::unique_ptr<STFT> stft; } ; //class STFT{}; Whatever::~Whatever() {} int main(){}
在定义任何定义的析构函数之前评论STFT的定义时,不满足要求,因为这需要stft的析构函数,这反过来要求STFT完成.
因此,在您的实现文件中,当Whatever :: ~Whatever()被定义时,STFT似乎已完成,否则在没有STFT完成的情况下创建默认的STFT.