Implementation of shared_ptr
Hi group!
I've got a question on the implementation of std::tr1::shared_ptr. In
the book titled Beyond C++ Standard Library, a simple technique to
prevent the deletion of raw pointer of shared_ptr is presented:
#include <iostream>
#include <tr1/memory>
using namespace std;
using namespace std::tr1;
class A
{
protected:
virtual ~A() { }
};
class B: public A
{
public:
virtual ~B() { }
};
int main()
{
shared_ptr<A> a(new B());
A *raw_a = a.get();
delete raw_a;
return EXIT_SUCCESS;
}
In this example, delete raw_a raises a compile time error because A's
destructor is protected. However, the following successfully compiles
and run:
int main()
{
shared_ptr<A> a(new B());
return EXIT_SUCCESS;
}
This means that, in shared_ptr, something like the following is
happening:
B *b = dynamic_cast<B*>(a.get());
delete b;
I searched for the source code, but I could not even find the
destructor. Moreover, AFAIK, shared_ptr is implemented like:
template<typename T>
class shared_ptr
{
T *t_;
public:
shared_ptr(T *t): t_(t) { }
template<typename Y>
shared_ptr(Y *y): t_(y) { }
...
};
The second construtor, which takes Y *y as an argument, is provided for
the situation where type conversion can happen like the one I've shown
above (storing new B() into shared_ptr<A>). And this implies that the
type information of Y is completely lost after y is assigned to t_.
That being the case, shared_ptr<A> a(new B()) can not deallocate the
memory because the deletition of a raw pointer of type A is a compile
time error.
So, I'm curious how shared_ptr is handling the deallocation of Y *y.
Could anybody give me some pointers?
Sincerely,
Minkoo Seo
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]