GCO4020/CSC428 - Advanced Object Oriented Techniques In C++
Week 3
The advantages of this technique for separating interface¤ and implementation¤ include:
MappingImpl class might instead be implemented as a static
STL¤ map - from MappingImpl pointers to pairs of data (see source code listing: HiddenMap.C), as follows:
class MappingImpl { private: friend class Mapping;
MappingImpl(string name, int value) { ourMap[this] = NV(name,value); }
void SetName(string name) { ourMap[this].first = name; } string GetName(void) { return ourMap[this].first; }
void SetValue(int value) { ourMap[this].second = value; } int GetValue(void) { return ourMap[this].second; }
typedef pair<string,int> NV; static map<MappingImpl*, NV, less<MappingImpl*> > ourMap; };
// DEFINITION OF STATIC MAP...
map<MappingImpl*, MappingImpl::NV, less<MappingImpl*> > MappingImpl::ourMap;
This technique, which is sometimes called "Flyweight objects" (Gamma et al. 1995, § 4), minimizes the size of each
MappingImpl object, and hence the cost of allocating such
objects. This approach also provides a means of accessing every such
object sequentially (by iterating the map). This might be useful for
debugging purposes or if the Mapping class were to be made
persistent.
(End of solution)
Mapping destructor, by storing the pointer
to the MappingImpl object in an auto_ptr<MappingImpl>
(TDCS, § 20.4.5), rather than in a raw MappingImpl*.
This arrangement would work correctly without an explicitly defined Mapping
destructor, because the auto_ptr's destructor automatically deletes its
pointer when the auto_ptr itself is reclaimed as part of the (now
implicit) destruction of a Mapping object.
(End of solution)
For example, some compilers implement all references via pointers, which would eliminate the possibility of optimizing away the (now implicit) dereference required at each access.
Even if a compiler does generate different code for pointers and references,
its optimizer may not be able to deduce that the calls to myImpl.Get... and
myImpl.Set... may be inlined.
Last updated: Fri Feb 18 11:17:16 2000