Destructor in template class c : How to delete field which may be pointer or not pointer?

泪湿孤枕 提交于 2019-12-05 22:18:32

You can develop two versions for your template. First, write the normal version template<class T>. Then, write a second pointer-only version that specializes your template by declaring it like this:

template<class T>
class TArray<T*>

Inside the destructor, you can use std::is_pointer and only delete[] the data then.

The preferred alternative is to not manage memory yourself though (use std::vector or smart pointers).

If you replace the raw pointers with std::unique_ptr or std::shared_ptr, the problem vanishes.

(If that's not what you want, then think twice about whether TArray should be managing this at all. Who will guarantee that the pointers stored in a TArray<T*> have been allocated with new? There's no RAII solution to that problem.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!