Compiled Example:
main.cpp
#include "test.h" int main(int argc, char* argv[]) { auto myPtr = std::unique_ptr<MyClass>(getMyPtr()); }
test.h
#ifndef TEST_H #define TEST_H #include <memory> class MyClass; extern template class std::unique_ptr<MyClass>; MyClass* getMyPtr(); #endif
test.cpp
#include "test.h" class MyClass {}; template class std::unique_ptr<MyClass>; MyClass* getMyPtr() { return new MyClass; }
g ++ 4.9.2 complains
In file included from c:/devel/mingw32/i686-w64-mingw32/include/c++/memory:81:0, from main.cpp:4: c:/devel/mingw32/i686-w64-mingw32/include/c++/bits/unique_ptr.h: In instantiation of 'void std::default_delete<_Tp>::operator()(_Tp*) const [with _Tp = MyClass]': c:/devel/mingw32/i686-w64-mingw32/include/c++/bits/unique_ptr.h:236:16: required from 'std::unique_ptr<_Tp, _Dp>::~unique_ptr() [with _Tp = MyClass; _Dp = std::default_delete<MyClass>]' main.cpp:64:53: required from here c:/devel/mingw32/i686-w64-mingw32/include/c++/bits/unique_ptr.h:74:22: error: invalid application of 'sizeof' to incomplete type 'MyClass' static_assert(sizeof(_Tp)>0, ^
although MyClass should be visible at the time the template is created. Why?
Edit: fixed a typo in the example.
c ++ c ++ 11 templates forward-declaration incomplete-type
Smiles
source share