You can use some of the features of C ++ 11 to make it more portable, but this may be sufficient as a starting point:
Class
template<typename T> class t_secure_destruct { static const size_t Size = sizeof(T); static const size_t Align = alignof(T); public: t_secure_destruct() : d_memory() { new(this->d_memory)T; } ~t_secure_destruct() { reinterpret_cast<T*>(this->d_memory)->~T(); this->scribble(); }
Demo
#include <iostream> class t_test { public: t_test() : a(-1) { std::cout << "construct\n"; } ~t_test() { std::cout << "destruct\n"; } public: void print() const { std::cout << "a = " << a << "\n"; } public: int a; }; int main(int argc, const char* argv[]) { t_secure_destruct<t_test>test; test.get().print(); test.get().a = 100; test.get().print(); return 0; }
Of course, you could also return this distribution with a heap distribution if you want. If you need to outsmart the optimizer, you may need to take it out of reach.
source share