c++ - 为什么 "error: invalid application of ' sizeof' 为使用 unique_ptr 的不完整类型”通过添加空析构函数来修复?

标签 c++ c++11 unique-ptr pimpl-idiom

<分区>

我在类里面拉皮条STFT .在 header 中用这个编译就好了:

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;在 header 中的原始指针上,并删除析构函数,我得到

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 的 cppreference 文档:

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(){}

如果在定义 Whatever 的析构函数之前注释了 STFT 的定义,则不满足要求,因为这需要 stft 的析构函数这反过来又需要 STFT 才能完成。

因此,当 Whatever::~Whatever() 被定义时,您的实现文件STFT似乎很可能是完整的,否则默认一个是在 STFT 不完整的情况下创建的。

关于c++ - 为什么 "error: invalid application of ' sizeof' 为使用 unique_ptr 的不完整类型”通过添加空析构函数来修复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34072862/

相关文章:

c++ - 为什么 std::array 没有一个构造函数来为要填充的数组取一个值?

c++ - 将 args 应用于函数的模板函数

c++ - 自动生成唯一的类型 ID,反之亦然

c++ - 我如何 move std::unique_ptr 作为构造函数参数?

c++ - 给定一个 vector ,删除低于 itemnum 的元素

c++ - Valgrind 检测 strlen 中的无效读取

c++ - 函数模板特化被忽略

C++ variadic 可变参数模板参数的数量

c++ - 如何在 Google Mock 中模拟返回类型为 unique_ptr 的方法?

c++ - unique_ptr 与 vector : error: call to implicitly-deleted copy constructor of XXX