* Sean:
Agreed. It's not a good idea. However, I still need to do it. Can you
post sample code on how to do it?
Note first that normally you'd just use another shared_ptr to keep a
reference to the original's referred object.
And when that isn't feasible, you'd normally use boost::weak_ptr.
I'm therefore almost certain that what you're trying to do is Very Bad
Design (TM), that you could very easily solve the problem by improving the
design, but if you absolutely want to live extremely dangerously, e.g.
#include <iostream>
#include <ostream>
#include <boost/shared_ptr.hpp>
class X
{
public:
typedef boost::shared_ptr<X> AutoPtr;
static AutoPtr instance(){ return AutoPtr( new X, &destroy ); }
~X(){ std::cout << "Destroyed" << std::endl; }
X* extendedLifetime() { myExtendedLife = true; return this; }
private:
bool myExtendedLife;
X(): myExtendedLife( false ) { std::cout << "Created" << std::endl; }
static void destroy( X* p ) { if( !p->myExtendedLife ){ delete p; } }
};
void doStuff( X::AutoPtr ) {} // Whatever.
X* aUsedNewX()
{
X::AutoPtr p( X::instance() );
doStuff( p );
return p->extendedLifetime();
}
int main()
{
// C-oriented calling code.
X* p = aUsedNewX();
std::cout << "main()" << std::endl;
delete p;
}
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?