现在我首先了解unique_ptr<>的一般问题和前进的声明如
Forward declaration with unique_ptr?.
考虑这三个文件:
啊
#include <memory> #include <vector> class B; class A { public: ~A(); private: std::unique_ptr<B> m_tilesets; };
C.cpp
#include "A.h" class B { }; A::~A() { }
main.cpp中
#include <memory> #include "A.h" int main() { std::unique_ptr<A> m_result(new A()); }
发出g -std = c 11 main.cpp C.cpp会产生以下错误:
In file included from /usr/include/c++/4.8/memory:81:0,from main.cpp:1: /usr/include/c++/4.8/bits/unique_ptr.h: In instantiation of ‘void std::default_delete<_Tp>::operator()(_Tp*) const [with _Tp = B]’: /usr/include/c++/4.8/bits/unique_ptr.h:184:16: required from ‘std::unique_ptr<_Tp,_Dp>::~unique_ptr() [with _Tp = B; _Dp = std::default_delete<B>]’ A.h:6:7: required from here /usr/include/c++/4.8/bits/unique_ptr.h:65:22: error: invalid application of ‘sizeof’ to incomplete type ‘B’ static_assert(sizeof(_Tp)>0,
这是真的,B是A.h的第6行不完整的类型 – 但这不是A的析构函数!即使我提供一个,似乎也为A生成了一个析构函数. A的析构函数在C.cpp行7中,B是完全定义的类型.为什么我得到这个错误?
解决方法
您还需要将A.的构造函数放在C.cpp中:
啊
#include <memory> #include <vector> class B; class A { public: A(); ~A(); private: std::unique_ptr<B> m_tilesets; };
C.cpp
#include "A.h" class B { }; A::~A() { } A::A() { }
请参见this answer.构造函数还需要访问完整类型.这样就可以在构造过程中抛出异常时调用该删除器.