allow only objects to be generated inside the heap? How do you understand that? Do you have a swollen handle? If there is a class person on hand, when you write the person RN in the program, the compiler quietly does two things: Call the constructor construct object RN, and at the time of the stack, call the destructor destructor Rn. The construction and destruction of the object RN is entirely the responsibility of the compiler, which is the property of the stack! As is known to all, the object RN is generated in the stack. And what are we asking for now? "Only allow objects to be generated inside the heap. "RN is a clear violation of our requirements, which means it should be banned. What about this "pit-daddy" thing? Some people want to say that it is OK to have the constructor or destructor of person as private. Perhaps a lot of people really have this first thought, if so, I think further down. If that is the case, can this class implement inheritance? No, that is, the prohibition of inheritance. Also, does this class allow other classes to have its objects? No, that is, the prohibition is included. What about that? The solution is also very simple, the side-effect of the release of the inheritance of the person's destructor can only be protected; resolve the included side effects simply make the member variable PS in test a person* Type and in test construction/The initialization and release of member variables in destructors is possible. The complete code for this example is shown below. #include<iostream>using namespacestd;classperson{ Public: Person () {cout<<"Con ()"<<Endl; } person (intx) {a=x; cout<<"Con (x)"<<Endl; } voidDestroy () {Delete This; }protected: ~Person () {cout<<"Des"<<Endl; }Private: intA;};classStudent: Publicperson{};classtest{ Public: Test () {PS=NewPerson ();//objects on the heap } ~Test () {PS-Destroy (); }Private: person*PS;};voidMain () {Test T1;}
Reprinted from: http://www.cnblogs.com/Braveliu/archive/2013/01/06/2847475.html
Only allow objects to be generated inside the heap