Program correction using unique_ptr
livecode
Task condition
The program terminates with an error because the std::unique_ptr<Impl> member m_impl in class Example is incomplete at the point of its declaration in the header file. In C++, you cannot instantiate or delete a std::unique_ptr to an incomplete type unless the destructor of the class is fully defined where the unique_ptr is destroyed.
To fix this, you should define the destructor of Example in the source file (Example.cpp) where the complete type Impl is known. This ensures that the destructor of Example (which implicitly destroys m_impl) is complete and can correctly delete the Impl object.
Corrected approach:
In Example.h, declare the destructor explicitly:
class Example
{
public:
Example(int);
~Example(); // declare destructor
struct Impl;
std::unique_ptr<Impl> m_impl;
};
In Example.cpp, define the destructor:
Example::~Example() = default;
This way, the destructor is defined where Impl is complete, allowing proper destruction of m_impl.