Is std::unique_ptr required to know the full definition of T?

前端 未结 9 1358
小鲜肉
小鲜肉 2020-11-22 07:47

I have some code in a header that looks like this:

#include 

class Thing;

class MyClass
{
    std::unique_ptr< Thing > my_thing;
};
         


        
9条回答
  •  名媛妹妹
    2020-11-22 07:52

    Just for completeness:

    Header: A.h

    class B; // forward declaration
    
    class A
    {
        std::unique_ptr ptr_;  // ok!  
    public:
        A();
        ~A();
        // ...
    };
    

    Source A.cpp:

    class B {  ...  }; // class definition
    
    A::A() { ... }
    A::~A() { ... }
    

    The definition of class B must be seen by constructor, destructor and anything that might implicitely delete B. (Although the constructor doesn't appear in the list above, in VS2017 even the constructor needs the definition of B. And this makes sense when considering that in case of an exception in the constructor the unique_ptr is destroyed again.)

提交回复
热议问题