“Use of undefined type” with unique_ptr to forward declared class and defaulted move constructor/assignment

半腔热情 提交于 2021-02-17 05:45:24

问题


In the following code, is the only way to avoid a compile error and to include B.h implementing the move constructor / assignment manually in A.cpp?

// A.h
#include <memory>
class B; // implementation somewhere in B.h/B.cpp
class A
{
public:
    A() = default;
    ~A() = default;
    A(const A&) = delete;
    A& operator=(const A&) = delete;
    A(A&&) = default;
    A& operator=(A&&) = default;

private:
    std::unique_ptr<B> m_b;
};

Visual Studio 2015 gives "error C2027: use of undefined type", since the move constructor/assignment operator of std::unique_ptr calls the deleter on m_b (trying to invoke B's destructor), which is obviously not known at this point.


回答1:


Yes, you need to have access to the full definition of B from wherever you instantiate std::unique_ptr<B>::~unique_ptr, because it needs to call B's destructor.

In your case, that means that A::~A's definition must be moved to a separate A.cpp file, which includes B.h.



来源:https://stackoverflow.com/questions/63986179/forward-declaration-and-unique-ptr

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!