ObjDef.h
1 /* 2 * 3 * Date: 2019.09.07 4 * 5 */ 6 7 #ifndef _H_H_OBJ_DEF_H_H_ 8 #define _H_H_OBJ_DEF_H_H_ 9 10 #include <iostream> 11 12 class ObjA 13 { 14 public: 15 ObjA() { std::cout << "Construct ObjA" << std::endl; } 16 ~ObjA() { std::cout << "Destruct ObjA" << std::endl; } 17 }; 18 19 class ObjB 20 { 21 public: 22 ObjB() { std::cout << "Construct ObjB" << std::endl; } 23 ~ObjB() { std::cout << "Destruct ObjB" << std::endl; } 24 }; 25 26 class ObjC 27 { 28 public: 29 ObjC() { std::cout << "Construct ObjC" << std::endl; } 30 ~ObjC() { std::cout << "Destruct ObjC" << std::endl; } 31 }; 32 33 #endif
Problem Description:
If there are a plurality of objects, each object is how to control the initialization and destruction?
method 1:
Using a pointer.
The following code:
1 /* 2 * 3 * Date: 2019.09.07 4 * 5 */ 6 7 #include <iostream> 8 9 #include "ObjDef.h" 10 11 int main() 12 { 13 ObjA* pAObj = NULL; 14 ObjB* pBObj = NULL; 15 ObjC* pCObj = NULL; 16 17 // Frist initialize ObjB object. 18 pBObj = new ObjB(); 19 20 // Next ObjC 21 pCObj = new ObjC(); 22 23 // Next ObjA 24 pAObj = new ObjA(); 25 26 std::cout << "Hello World" << std::endl; 27 28 // Frist free ObjC 29 delete pCObj; 30 31 // Next ObjA 32 delete pAObj; 33 34 // Next ObjB 35 delete pBObj; 36 37 38 return 0; 39 }
Results of the:
to sum up:
When using the new keyword, allocated objects, call the object constructor.
When using the delete key, call the object destructor, release the memory occupied by the object.
Method 2:
Use local static objects. The following code shown in FIG.
1 #include <iostream> 2 3 #include "ObjDef.h" 4 5 ObjA& theObjA() 6 { 7 static ObjA a; 8 return a; 9 } 10 11 ObjB& theObjB() 12 { 13 static ObjB b; 14 return b; 15 } 16 17 ObjC& theObjC() 18 { 19 static ObjC c; 20 return c; 21 } 22 23 24 int main() 25 { 26 // Frist ObjA 27 ObjA &a = theObjA(); 28 29 // Next ObjC 30 ObjC& c = theObjC(); 31 32 // Next ObjB 33 ObjB& b = theObjB(); 34 35 std::cout << "Hello World" << std::endl; 36 }
Results of the:
Analyzed:
Use local static objects, when calling the related function, complete the initialization of object, completed main function is executed, it will be released in reverse order.