Apologies for the off-topic nature, but you're the best C++ programmers I 
know ;-)

Boost has shared_ptr and shared_c_ptr and scoped_ptr but no scoped_c_ptr 
which leads to the thought that actually all these are the same, save for the 
function they call in their d-tor.

So why don't they parameterise that function? You could imagine this 
parameterised scoped_ptr  calling some arbitrary function as it goes out of 
scope. Fantastic, for example, if I'm using c-style structs that contain 
pointers themselves and that have been malloc-ed into existence.

I wrote a small piece of example code that does this. Attached.

Question is, am I being daft, or should I send my inspiration to boost ;-)

Angus
namespace boost {

class noncopyable {
protected:
        noncopyable(){}
        ~noncopyable(){}
private:
        noncopyable( const noncopyable& );
        const noncopyable& operator=( const noncopyable& );
};

template< typename T >
inline void checked_delete(T * x)
{
        //BOOST_STATIC_ASSERT( sizeof(T) != 0 );
        delete x;
}

template< typename T >
struct CheckedDelete {
	void operator()(T * x) { checked_delete(T); }
};
	

template<typename T, typename Destroy=CheckedDelete<T> >
class scoped_ptr : noncopyable {
	static Destroy destroy;

	T* ptr;

public:
	typedef T element_type;

	explicit scoped_ptr( T* p=0 )
		: ptr(p)
	{}

	~scoped_ptr()
	{
		destroy(ptr);
	}

	void reset( T* p=0 )
	{
		if ( ptr != p ) {
			destroy(ptr);
			ptr = p;
		}
	}

	T& operator*() const  { return *ptr; }
	T* operator->() const { return ptr; }
	T* get() const        { return ptr; }
};

} // namespace boost

#include <iostream>

struct Foo {
	Foo() : a(0), b(0) {}
	int a;
	int b;
};

std::ostream & operator<<(std::ostream & out, Foo const & foo)
{
	out << foo.a << ' ' << foo.b;
	return out;
}

template< typename T >
struct PrintAndDelete {
	void operator()(T * x)
	{
		std::cout << *x << std::endl;
		delete x;
	}
};
	

int main () 
{
	boost::scoped_ptr<Foo, PrintAndDelete<Foo> > foo(new Foo);
	foo->a = 1;
	return 0;
}

Reply via email to