C++ Reseatable Reference

After reading this article and being inspired, I decided to write a simple “reseatable_reference” class that’s sort of like boost::weak_ptr but lighter weight. The idea is that I often use pointers as reseatable references, since in C++ references cannot be reseated. So I created a reseatable_references class that’s basically a wrapper around a pointer but nicer to use that putting pointers all through my code along with the baggage they create (initializing them to NULL, asserting that they aren’t NULL all over the place, etc). Here’s the entire content of the class:

template 
class reseatable_reference
{
	private:
		T * ptr;
		
		bool valid() const {return ptr;}
		
	public:
		reseatable_reference() : ptr(NULL) {}
		reseatable_reference(T & ref) : ptr(&ref) {}
		
		operator bool() const {return valid();}
		
		T & get() {assert(valid());return *ptr;}
		void set(T & ref) {ptr = &ref;}
		reseatable_reference  & operator=(T & other)
		{
			set(other);
			return *this;
		}
};

Comments are closed.

Dev Journal and Project Hosting