Can't use std::unique_ptr with T being a forward declaration

前端 未结 2 934
梦毁少年i
梦毁少年i 2021-01-07 18:46

Now first, I am aware of the general issues with unique_ptr<> and forward declarations as in Forward declaration with unique_ptr? .

Consider these three files:

相关标签:
2条回答
  • 2021-01-07 19:22

    The implicitly defined special member functions are inline, leading to issues with incomplete types. As the link from Chris's answer shows, all non-delegating constructors could potentially invoke the destructor. This includes copy(deleted in this case) and move constructors as well. So, when you are dealing with non-static members involving incomplete types, explicitly default the definitions in the source file, thus ensuring that they aren't defined inline.

    In header:

    A();
    ~A();
    A(const A&);
    A(A&&);
    

    In source:

    A::A() = default;
    A::~A() = default;
    A::A(const A&) = default;
    A::A(A&&) = default;
    
    0 讨论(0)
  • 2021-01-07 19:39

    You also need to put A's constructor in C.cpp:

    A.h

    #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() {
    
    }
    

    See this answer. The constructor needs access to the complete type as well. This is so that it can call the deleter if an exception is thrown during construction.

    0 讨论(0)
提交回复
热议问题