I have a factory function in factory.h which returns an std::shared_ptr
to a base class in foo.h. factory.h uses forward declaration to the base class instead of including foo.h. As the following code:
factory.h:
#include <memory>
// forward declaration
class foo;
std::shared_ptr<foo> create_foo_A(int A);
std::shared_ptr<foo> create_foo_B(int A, int B);
void work_with_foo(std::shared_ptr<foo> ptr);
In a client code, if a std::shared_ptr<foo>
was initialized with nullptr
the compiler would warn.
main.cpp:
#include "factory.h"
int main()
{
int type = 1;
std::shared_ptr<foo> ptr(nullptr); // <--- compile warning
if (type == 1)
ptr = create_foo_A(5566);
else
ptr = create_foo_B(5566, 7788);
work_with_foo(ptr);
return 0;
}
The warning message is:
warning C4150 : deletion of pointer to incomplete type 'foo'; no destructor called
It's reasonable since the std::shared_ptr
doesn't know the complete type of foo. This warning can be removed if main.cpp includes foo.h.
But if std::shared_ptr
was initialized with non-nullptr
, the compiler wouldn't warn.
main.cpp:
#include "factory.h"
int main()
{
int type = 1;
if (type == 1)
{
std::shared_ptr<foo> ptr = create_foo_A(5566); // <--- OK
work_with_foo(ptr);
}
else
{
std::shared_ptr<foo> ptr = create_foo_B(5566, 7788); // <--- OK
work_with_foo(ptr);
}
return 0;
}
In this scene, why doesn't std::shared_ptr
need to know the complete type of class foo
? Is it very different when std::shared_ptr
is constructed with nullptr
and non-nullptr
?