Only objects generated by new

zhaozj2021-02-16  65

The object generated with NEW is useful in the object-oriented object. It is saved on the heap and can freely control the life cycle.

But how can I ensure that an object can only be generated on the pile?

The answer is actually very simple, just defines the destructor as a private member. For example, OnlycanBenew definitions.

1 | Class ONLYCANBENEW

2 | {

3 | ~ onlinecanbenew () {}

4 | Public:

5 | Onlycanbenew () {}

6 |};

The reason, C is a static bound language. During the compilation process, all non-virtual functions must be analyzed. Even virtual functions, you also need to check accessibility. Because of the objects, the object will automatically analyze when the object is generated on the stack, and the destructor must be accessible. The object is generated on the pile, since the designer is controlled by programmer, so it does not necessarily require a destructive function.

It is guaranteed that after the object cannot be generated on the stack, it needs to be proved to generate it on the heap. The only difference between ONLYCANNEW and the general object here is that its destructor is private. The DELETE operation will call the destructor. So you can't compile. So how do I release it?

The answer is also very simple, providing a member function to complete the DELETE operation. In a member function, the destructor can be accessed. Of course, the Detle operation can also be compiled.

7 | Void Onlycanbenew :: destroy ()

8 | {

Delete this;

10 |}

Go back to the starting point, if you need to use this object on the stack, what should I do? Then use it to pack it. Similar to the WRAP class, if it is the same as the OnlycanBenew interface. Then use it on the stack, just like OnlyCanbenew.

11 | #include

12 |

13 | CLASS WRAP;

14 | Class Onlycanbenew

15 | {

16 | Friend Class Wrap;

17 | ~ Onlycanbenew () {}

18 | Public:

19 | Onlycanbenew () {}

20 | void destroy ()

21 | {

22 | DELETE THIS;

23 |}

24 |};

25 |

26 | CLASS WRAP

27 | {

28 | Onlycanbenew * P;

29 | Public:

30 | wrap (): P (New Onlycanbenew)

31 | {

32 |}

33 |

34 | ~ WRAP ()

35 | {

36 | P-> Destroy ();

37 |}

38 |

39 |};

The test code is as follows:

40 | Int main (int Argc, char * argv [])

41 | {

42 | OnlycanBenew One; // Compiling errors

43 |

44 | Wrap Some; // OK

45 | Onlycanbenew * p = new online on

46 |

47 | P-> destroy (); // Release

48 | Printf ("Hello, WORLD / N");

49 |

50 | Return 0; 51 |}

转载请注明原文地址:https://www.9cbs.com/read-15603.html

New Post(0)