You always have random access to some set of variables defined in some scope, and you always loose these variables when you leave the stack frame where they are defined.
Perhaps you mean something else, such as class members. But then it all depends on what are they. If these are static members, you cannot remove them. If they are
instance members, the belong to a particular instance of a class, so as soon as you delete the instance, you loose all instance members and its values. So, it gives you the first option: you work with some instance and some members (fields) and then use their values somehow, say, copy the values to some other instance of the same or another class (you can keep them read-only after initialization of them or the second instance), and then you delete the instance you worked with.
Another option with class fields is this: make them non-public, and provide public (friend?) access to them in the indirect fashion, through
accessor methods. In its simplest form, for the field type T, it can be
T get*()
and void
set*(T)
instance methods. (I use '*' symbol as a
wildcard for a name, not as pointer here :-).) Per each instance member, you can have only
getter, or only
setter, or both, depending on your purpose. Apparently, the accessors can add some
side effect to your field assignment and read operations.
(By the way, see this interesting CodeProject article discussing C#-like properties for C++, it can make this concept clear to you:
C++11 Properties[
^].)
Now, this side-effect could be blocking access to assignment a value to a field or reading it, after your instance enters next "get rid of used members" state. I hope implementation of such effect should be obvious.
—SA