开发者

C++ destructor format

开发者 https://www.devze.com 2023-02-08 17:54 出处:网络
void arrayLis开发者_运维百科t<T>::erase(int theIndex) { // valid index, shift elements with higher index
 void arrayLis开发者_运维百科t<T>::erase(int theIndex) {
            // valid index, shift elements with higher index
            copy(element + theIndex + 1, element + listSize, element + theIndex);

            element[--listSize].~T(); // invoke destructor 
        }

The code element[--listSize].~T() looks strange. It is used to delete the dynamically allocated element. Does any know why we can use this syntax?

EDIT

The problem is solved.


That would be useful if you have allocated memory for elements[i] using placement new operator. See What is "placement new" and why would I use it? for details.


Does any know why we can use this syntax?

We use it to invoke the destructor on an object allocated with placement new, generally. See also this page.


Explicitly calling the destructor is useful in cases where you want to properly destruct the object, but not deallocate it's memory by using delete (or delete[]) directly, such as inside some custom memory manager. It should not be used very often though.


The code element[--listSize].~T() looks strange. It is used to delete the dynamically allocated element. Does any know why we can use this syntax?

It is used to destroy that object; this is probably what you meant, but "delete" has other meanings in C++. You need to do this if you construct each item manually.

You can use this syntax because it is specifically allowed by the language. The opposite of a manual destructor call is placement new.


Yes you are correct they are explicitly invoking the destructor ...

However you can fix all of the problems with this implementation by throwing it out and using std::vector or std::list instead!

0

精彩评论

暂无评论...
验证码 换一张
取 消