M
mike.polyakov
I have trouble understanding incomplete types and their interplay with
shared_ptr. Consider the following code, composed of two source files
and one header:
//------------------------------------------------------------------
// test.h
#ifndef TEST_H_
#define TEST_H_
#include <boost/shared_ptr.hpp>
using namespace boost;
struct A;
struct B
{
shared_ptr<A> p;
B();
~B();
};
#endif
//------------------------------------------------------------------
// test1.cpp
#include "test.h"
#include <iostream>
using namespace std;
struct A {
~A();
};
A::~A() { cout <<"Destruct A" <<endl; }
B::B() : p(new A) {}
//------------------------------------------------------------------
// test2.cpp
using namespace std;
using namespace boost;
#include "test.h"
B::~B() { }
int main()
{
B b;
return 0;
}
//------------------------------------------------------------------
From my understanding the above should not compile. A is incomplete in
test2.cpp. Instantiation of shared_ptr<A> destructor should happen
during compilation of B's destructor. Since B's destructor is declared
in test2.cpp, the instantiation of shared_ptr<A> destructor should
cause checked_delete to be applied to incomplete type A and fail.
However, it doesn't and this compiles and runs correctly. However,
adding two lines
A *a;
shared_ptr<A> p(a);
to main() in test.cpp generates a compile error, which of course it
should. I am confused. Could anyone clarify this for me please?
Thanks.
shared_ptr. Consider the following code, composed of two source files
and one header:
//------------------------------------------------------------------
// test.h
#ifndef TEST_H_
#define TEST_H_
#include <boost/shared_ptr.hpp>
using namespace boost;
struct A;
struct B
{
shared_ptr<A> p;
B();
~B();
};
#endif
//------------------------------------------------------------------
// test1.cpp
#include "test.h"
#include <iostream>
using namespace std;
struct A {
~A();
};
A::~A() { cout <<"Destruct A" <<endl; }
B::B() : p(new A) {}
//------------------------------------------------------------------
// test2.cpp
using namespace std;
using namespace boost;
#include "test.h"
B::~B() { }
int main()
{
B b;
return 0;
}
//------------------------------------------------------------------
From my understanding the above should not compile. A is incomplete in
test2.cpp. Instantiation of shared_ptr<A> destructor should happen
during compilation of B's destructor. Since B's destructor is declared
in test2.cpp, the instantiation of shared_ptr<A> destructor should
cause checked_delete to be applied to incomplete type A and fail.
However, it doesn't and this compiles and runs correctly. However,
adding two lines
A *a;
shared_ptr<A> p(a);
to main() in test.cpp generates a compile error, which of course it
should. I am confused. Could anyone clarify this for me please?
Thanks.