Click here to Skip to main content
Click here to Skip to main content
 
Add your own
alternative version

Saving a variable temporarily

, 16 Nov 1999
A safe, and convenient way to store variables temporarily
save_temp_var.zip
// 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

Share

About the Author

Alvaro Mendez
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#.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.1411028.1 | Last Updated 17 Nov 1999
Article Copyright 1999 by Alvaro Mendez
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid