+ 1

What is the best for class or struct destructor?

Hi everyone. Usually I use something like memset(this, NULL, sizeof(*this)); to clear used memory after destructing my classes or structs. But this method is so old cause it from C and I think there is more correct, fast and safe way for C++. Tell me please how I can to clear memory not using that method?

1st Aug 2019, 10:02 PM
Arseniy Bechin
Arseniy Bechin - avatar
1 Odpowiedź
+ 3
Generally after some object has been destructed (you call on allocated object delete/delete[]) it is freed and available for new allocations. You should clear the memory (fill it with zeroes) if you store in that place sensitive data like password, encryption keys etc. memset can do the job in C++ too, BUT, it can be still optimized away! If you destroy object, compiler might remove memset instruction if object previously destroyed isn't accessed anymore. To protect from that you have to use memset_s (or some third party solution). Answering your question, don't clean memory at all. It doesn't matter if you leave some data in it anyway, unless, it is sensitive data. If it is sensitive data use memset_s which won't be optimized away.
1st Aug 2019, 10:43 PM
Mateusz R
Mateusz R - avatar