Templace
Struct People {
T the info;
People * last;
People * next;
People ()=default;
~ People () the default;
};
For such a structure, used to store data in another class, then the class has a remove function to remove some index data
Template
The class PeopleList {
Private:
People* allPeople;
//...
Public:
Void the remove (STD: : size_t index);
};
Template
Void PeopleList: : remove (STD: : size_t index) {
People* TMP=allPeople;;
STD: : size_t currentIndex=0;
While (currentIndex!=(index - 1)) {
TMP=TMP - & gt; The last;
+ + currentIndex;
}
TMP - & gt; T: : ~ (T);//?? How to call People's destructor
Delete the TMP;
}
For composed of multiple People list, I want to delete one of the elements, to do step 2
1. Call People destructor, because People in the info may be also applied to memory
2. Delete People's memory
That how to call People's destructor
CodePudding user response:
Why have malloc and free C, C + + requires new delete?Because new automatically calls the constructor, delete automatically calls the destructor,
Delete TMP, the destructor call ~ People automatically, need not show called
If you use the place new, need to display calls the constructor and destructor
For example,
BYTE * pb=new BYTE [sizeof (STD: : string)];
((STD: : string *) pb) - & gt; STD: : basic_string & lt; Char, STD: : char_traits & lt; Char> , STD: : allocator
((STD: : string *) pb) - & gt; STD: : basic_string & lt; Char, STD: : char_traits & lt; Char> , STD: : allocator
Really want to call the destructor template (the above example has given STD: : string template examples)
TMP - & gt; People
CodePudding user response:
It is ok to directly deleteCalled automatically delete TMP TMP destructor, and deleted in the destructor of TMP TMP contains memory
CodePudding user response:
What's the difficult?Delete allPeople PeopleList
TMP - & gt; T: : ~ (T);//this is the error code, don't need to delete will automatically call
Delete the TMP;