1, consider the following requirements, a set of different types, but interrelated objects into the container, such as the Animal,dog,cat object.
2. A container can contain only one set of objects of the same type, and the Animal,dog,cat object cannot be placed in the container.
3, how to solve the above problem?
Assuming that the container is a vector, you can use Vector<animal>, which leads to a new problem, because the vector stores a copy of the object, and the subclass puts the object cut in the vector<animal>, which is unlikely to have polymorphic properties.
How to solve the above problem?
--------------------------------------------------------------------------------------------------------------- ------
The Classic solution:
The animal pointer is stored in the vector, which brings up the following problems:
1, Dog D; V.push_back (&D); D is a local object, the left scope is automatically destroyed, and the pointer in the container points to a heap of garbage.
2, in order to solve the above problem, use V.push_back (new Dog (d)); This will bring the burden of dynamic memory management, consider assigning v[j] to V[i],
3, V[j] = v[i]; Two pointers point to the same object, V[j] and v[i] do not know each other, are not released, memory leaks, are released, the behavior is undefined.
4, to V[i] make a copy, because do not know the true type of v[i], using v[j] = new Animal (V[i]); This again occurs with object cutting.
5, solve the object of the cut, using the virtual clone method, as follows: v[j] = V[i].clone ();
--------------------------------------------------------------------------------------------------------------- ------
Using the proxy class, the pointer is animal* encapsulated, and the object on the stack manages dynamic memory, enabling the automatic release of pointers.
As follows:
animalproxy::animalproxy (): _pa (NULL) {}animalproxy::~Animalproxy () {Delete_pa;}//Note: You can access your private members in the class, or you can access the private members of RHSAnimalproxy::animalproxy (Constanimalproxy&RHS) {_PA= (Rhs._pa = = NULL? rhs._pa->Clone (): NULL);} Animalproxy& Animalproxy::operator=(Constanimalproxy&RHS) {if( This! = &RHS)//equivalent Test{Delete_PA;//Delete NULL also no problem_pa = (Rhs._pa = = null? Rhs._pa->clone (): null);//null-judged pointer}return* This;//return Reference}animalproxy::animalproxy (Constanimal&animal): _PA (animal. Clone ()) {}
"Meditations on C + +" proxy class