<分区>
让我们考虑以下示例(使用 c++11)
A.hpp:
#include <memory>
class A
{
public:
//A();
//~A();
private:
struct AImpl;
std::unique_ptr<AImpl> pImpl;
};
主要.cpp:
#include "A.hpp"
int main()
{
A a;
}
使用默认构造函数和析构函数。不编译。发生以下错误:
In file included from /usr/include/c++/4.8/memory:81:0, from A.hpp:2, from main.cpp:2: /usr/include/c++/4.8/bits/unique_ptr.h: In instantiation of 'void std::default_delete<_Tp>::operator()(_Tp*) const [with _Tp = A::AImpl]': /usr/include/c++/4.8/bits/unique_ptr.h:184:16: required from 'std::unique_ptr<_Tp, _Dp>::~unique_ptr() [with _Tp = A::AImpl; _Dp = std::default_delete]' A.hpp:3:7: required from here /usr/include/c++/4.8/bits/unique_ptr.h:65:22: error: invalid application of 'sizeof' to incomplete type 'A::AImpl'
static_assert(sizeof(_Tp)>0,
当使用 boost::scoped_ptr 而不是 std::unique_ptr 时会发生类似的错误。我是否理解正确 - 这意味着 AImpl 的前向声明是不够的?
添加构造函数和析构函数时,一切正常。是什么原因?是因为默认值是内联的,因此看不到 AImpl 的大小吗?在添加构造函数和析构函数时,编译器假定这些定义知道 AImpl 的大小?