|Welcome to the Monastery|
Re: On timely destruction?by TheDamian (Priest)
|on Aug 28, 2002 at 07:47 UTC||Need Help??|
A typical problem is how to wrap the accessor methods of a class, so that some check is performed once the returned value is dispensed with. For example, suppose you have to maintain some code that provides direct access to the "name" field stored within a CachedFile object. You might have:
But because the class gives out direct access to the name, you don't have control of it. If you need to ensure that the name doesn't exceed 12 characters in length, you have no way to do so; any changes to the name field will occur after CachedFile::name has finished:
One solution is not to return a reference to the name field at all. Instead, you return a reference to an imposter, which then forwards all requests to the real name field.
When the full expression in which this imposter was created is finished, the last reference to the imposter will disappear and its destructor will be called and can then check for foul play.
The class that implements the imposter – or "proxy" – looks like this:
The CachedFile class would then set up its name accessor like so:
Now any attempt to assign an extravagant name causes an exception to be thrown:
There are many such idioms that rely on proxy objects being destroyed at the end of the statement in which they're created (rather than at the end of the surrounding scope). So setting an end-of-scope action doesn't help these cases, since we want the effects to have been applied much earlier than that: before the next statement, in fact.