I'm concerned about using an incomplete type with a smart pointer and how the pointer is deleted. Is the following code safe? I don't think it would be, as main.cpp would generate Farm's default destructor which wouldn't see the complete type. To make it safe, I think I should create a non-inline destructor which sees the complete type. Is that correct?
Also is it the same if I used std::vector<Cow>
in Farm instead?
farm.h
class Cow;
struct Farm
{
Farm();
// ~Farm();
std::unique_ptr<Cow> cow;
};
farm.cpp
#include "cow.h"
// cow now complete
Farm::Farm()
{
cow.reset(new Cow);
}
// Farm::~Farm() {}
main.cpp
#include "farm.h"
int main()
{
Farm farm;
}
Edit: I tried to compile with Visual Studio without the destructor and it says error C2338: can't delete an incomplete type. I guess that answers my question.
auto_ptr
the code is bad, because the default destructor ofFarm
uses the destructor ofauto_ptr
, which just doesdelete
with the incomplete typeCow
. This has UB if the actual destructor ofCow
is non-trivial, and is valid otherwise. Since the compiler can't tell which it is (not having the definition ofCow
), it goes ahead and outputs the code. – Steve Jessop