This question follows a suggestion made by @sharptooth in this related question.
Can std::string be tweaked so that it becomes password-safe ?
If not, what would be the guidelines to write a password-handling class (thus a class that takes big care about what it writes to memory and clears it before destruction) ?
Yes, first define a custom allocator:
This allocator zeros the memory before deallocating. Now you typedef:
However there is a small problem, std::string may use small string optimization and store some data inside itself, without dynamic allocation. So you must explicitly clear it on destruction or allocate on the heap with our custom allocator:
This guarantees that all the data is zeroed before deallocation, including the size of the string, for example.