您可以使用一些 c++11 功能来使其更便携,但这可能足以作为起点:
班级
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();
}
// @todo implement or delete op-assign and remaining constructors
public:
T& get() {
return *reinterpret_cast<T*>(this->d_memory);
}
const T& get() const {
return *reinterpret_cast<const T*>(this->d_memory);
}
private:
void scribble() {
for (size_t idx(0); idx < Size; ++idx) {
this->d_memory[idx] = random();
}
}
private:
__attribute__((aligned(Align))) char d_memory[Size];
};
演示
#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;
}
当然,如果您愿意,您也可以使用堆分配来支持该分配。如果你需要比优化器更聪明,你可能需要把涂鸦器放在它够不到的地方。