【发布时间】:2014-03-09 01:58:53
【问题描述】:
让我们考虑以下示例(使用 c++11)
A.hpp:
#include <memory>
class A
{
public:
//A();
//~A();
private:
struct AImpl;
std::unique_ptr<AImpl> pImpl;
};
main.cpp:
#include "A.hpp"
int main()
{
A a;
}
使用默认构造函数和析构函数。不编译。出现以下错误:
在 /usr/include/c++/4.8/memory:81:0 包含的文件中, 来自 A.hpp:2, 来自 main.cpp:2: /usr/include/c++/4.8/bits/unique_ptr.h: 在 'void std::default_delete<_tp>::operator()(_Tp*) const [with _Tp = A::AImpl]': /usr/include/c++/4.8/bits/unique_ptr.h:184:16: 必需 来自 'std::unique_ptr<_tp _dp>::~unique_ptr() [with _Tp = A::AImpl; _Dp = std::default_delete]' A.hpp:3:7: 这里需要 /usr/include/c++/4.8/bits/unique_ptr.h:65:22: 错误: 无效 将“sizeof”应用于不完整类型“A::AImpl”
static_assert(sizeof(_Tp)>0,
使用 boost::scoped_ptr 而不是 std::unique_ptr 时会发生类似的错误。我是否理解正确 - 这意味着 AImpl 的前向声明还不够?
添加构造函数和析构函数时,一切正常。是什么原因?是因为默认值是内联的,因此看不到 AImpl 的大小吗?而在添加构造函数和析构函数时,编译器会假设这些定义知道 AImpl 的大小?
【问题讨论】:
-
this GOTW 对此问题进行了很好的讨论。
标签: c++ c++11 pimpl-idiom