|
Boost Users : |
From: Olaf Petzold (yg-boost-users_at_[hidden])
Date: 2002-08-27 08:57:27
Thanks for answers,
the const ptr was a fault.
Well, the following example shows the problem in detail:
----8<----
#include <iostream>
#include <boost/shared_ptr.hpp>
struct Spec {
Spec(const char* n) : m_name(n) { }
void member() const { std::cout << "Hold " << m_name << std::endl; }
const char* m_name;
};
struct SpecLP : public Spec {
SpecLP(const char* n) : Spec(n) { std::cout << "construct " << m_name <<
std::endl; }
~SpecLP() { std::cout << "destruct " << m_name << std::endl; }
};
struct SpecHP : public Spec {
SpecHP(const char* n) : Spec(n) { std::cout << "construct " << m_name <<
std::endl; }
~SpecHP() { std::cout << "destruct " << m_name << std::endl; }
};
struct Doc {
virtual ~Doc() { }
virtual void set(boost::shared_ptr<Spec>& ptr) = 0;
};
struct LpDoc : public Doc {
LpDoc() : m_lp( new SpecLP("LpDoc::lp") ) { }
void set(boost::shared_ptr<Spec>& spec) {
// m_lp = boost::shared_static_cast<SpecLP>( spec );
m_lp = boost::shared_polymorphic_cast<SpecLP>( spec );
}
void print() { m_lp->member(); }
boost::shared_ptr<SpecLP> m_lp;
};
struct HpDoc : public Doc {
HpDoc() : m_hp( new SpecHP("HpDoc::hp") ) { }
void set(boost::shared_ptr<Spec>& spec) {
// m_hp = boost::shared_static_cast<SpecHP>( spec );
m_hp = boost::shared_polymorphic_cast<SpecHP>( spec );
}
void print() { m_hp->member(); }
boost::shared_ptr<SpecHP> m_hp;
};
int main()
{
boost::shared_ptr<Spec> lp( new SpecLP("lp") );
boost::shared_ptr<Spec> hp( new SpecHP("hp") );
LpDoc doc;
std::cout << "Case 1:\n";
doc.print();
doc.set( lp ); // is O.K.
doc.print();
std::cout << "Case 2:\n";
try {
doc.print();
doc.set( hp ); // should throw
doc.print();
}
catch(const std::bad_alloc& e) {
std::cerr << "Exception \"" << e.what() << "\" catched\n";
}
}
---->8----
It doesn't compile with shared_ptr. Imho is the polymorph code correct
expect the pointer problem.
Thanks
Olaf
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net