03 March 2013

Forward Declaration And a Pointer

Mister C was a cool guy. C could make amazing things with just ordinary text files. He used to grab bunch of them and produce magic binary forms. He could make a spinning cube, web server, or even an operating system.
One time he was running through a plain header file. The day was calm and nothing portended a change. Suddenly mister C noticed one interesting line in the file.
class MyType;
"Cool" - he thought - "a forward declared type". After several other rather common statements that looked similar to this:
class Test
{
public:
    Test() { }
    ~Test() { }
    void doAll() { }
He focused on another piece of code:
private:
    std::unique_ptr<MyType> m_myType; 
}
After that line everything changed for mister C. He was so amazed by the code that all could do was to output a nasty error message.
Do you know what was the message? Why did he do that?

The message

In the output window (Visual Studio) there can be something like:
... while compiling class template member function
'void std::default_delete&lt;_Ty&gt;::operator ()(_Ty *) throw() const'
Or in the error list page:
error C2338: can't delete an incomplete type

Reason

Poor mister C had simply no idea how to delete object inside unique pointer. The deletion should happen in the destructor of the class MyTest of course. But since it was in the header file the problem arose.
Although mister C appreciated authors suggestion about forward declared type, his policy told him that at that point there has to be full type definition. Unique pointer required that, to be more specific its static deleter has to be defined properly.

Solution

Mister C cannot find proper solution, this is our task. To help him we can just move implementation of the destructor to some source file where the type MyType will be completely known. Simple as it is.
Another option is to use shared_ptr instead. Although it is a bit counter intuitive, the reason for that it simple. Shared pointer has dynamic deleter object that is selected at runtime, so there will be no errors at compile time.
Note that that when we create some object, we need to know full type definition of course.
Look below for more info about improving communication with you and mister C:
This post is just a quick addition to my previous post about Smart Pointer Gotchas.

Article is posted also on the CodeProject

Books related to this topic:

Interested in new blog posts and bonus content? Sign up for my newsletter.

© 2017, Bartlomiej Filipek, Blogger platform
Any opinions expressed herein are in no way representative of those of my employers.
This site contains ads or referral links, which provide me with a commission. Thank you for your understanding.