Click here to Skip to main content
15,881,424 members
Articles / Programming Languages / C++

Saving a variable temporarily

Rate me:
Please Sign up or sign in to vote.
3.93/5 (10 votes)
16 Nov 19993 min read 102.7K   1.4K   71  
A safe, and convenient way to store variables temporarily
// temp.h : header file for CTemp class
// Created by: Alvaro Mendez - 10/20/1999

#ifndef __TEMP_H__
#define __TEMP_H__


///////////////////////////////////////////////////////////////////////////////
// Variable-value saver class

// Class CTemp has a template constructor which allows you to save a 
// variable's current value (on construction) so that it can be restored 
// at a later time (on destruction).
//
// Sample usage:  CTemp v = variable_whose_value_you_are_saving;
//
class CTemp
{
public:
	// Base class for template class below.
	class SaverBase
	{
	public:
		virtual ~SaverBase() { }
		virtual void Restore() = 0;
	};

	// Template class which saves the value in construction
	// and restores it on destruction.
	template <class T>
	class Saver : public SaverBase
	{
	public:
		Saver(T& valueToSave) :
			m_ref(valueToSave),
			m_val(valueToSave)
		{ }

		virtual ~Saver()
		{
			Restore();
		}

		virtual void Restore()
		{
			m_ref = m_val;
		}

	private:
		T& m_ref;
		T m_val;
	};

public:
	template <class T> 
	CTemp(T& valueToSave) :
		m_pVar(new Saver<T>(valueToSave))
	{ }

	~CTemp()
	{
		Restore();
		delete m_pVar;
	}

	void Restore()
	{
		m_pVar->Restore();
	}

private:
	// Prevent accidental self copying
	CTemp(const CTemp&);
	CTemp& operator=(const CTemp&);  

protected:
	SaverBase* m_pVar;
};

#endif	// __TEMP_H__

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United States United States
I've done extensive work with C++, MFC, COM, and ATL on the Windows side. On the Web side, I've worked with VB, ASP, JavaScript, and COM+. I've also been involved with server-side Java, which includes JSP, Servlets, and EJB, and more recently with ASP.NET/C#.

Comments and Discussions