I'm developing a custom allocator for a simple and basic secure_string implementation in c++ based on https://en.cppreference.com/w/cpp/named_req/Allocator.
My code, as shown below, compiles and executes. However, I noticed that the allocate, deallocate methods of my allocator don't get executed. What am I missing?
static inline void secure_zero_memory(void *p, std::size_t n) noexcept
{
std::fill_n(static_cast<volatile unsigned char*>(p), n, 0);
}
template <typename T>
struct secure_allocator
{
using value_type = T;
secure_allocator() = default;
template <typename U>
secure_allocator(secure_allocator const&) noexcept {}
template <typename U>
secure_allocator& operator=(secure_allocator<U> const& ) { return *this;}
// define rebind structure for allocator
template <class U>
struct rebind { typedef secure_allocator<U> other; };
T* allocate(std::size_t n)
{
std::cout << "Allocating " << n << " bytes\n";
return std::allocator<T>{}.allocate(n);
}
void deallocate(T *p, std::size_t n) noexcept
{
secure_zero_memory(p, n * sizeof (*p));
std::cout << "secure_zeroed memory, deleting buffer\n";
std::allocator<T>{}.deallocate(p, n);
}
};
template <typename T, typename U>
constexpr bool operator==(secure_allocator<T> const&, secure_allocator<U> const&)
{
return true;
}
template <typename T, typename U>
constexpr bool operator!=(secure_allocator<T> const&, secure_allocator<U> const&)
{
return false;
}
using secure_string = std::basic_string<char, std::char_traits<char>, secure_allocator<char> >;
The cout statements above do not produce any output. Here's an example usage
{
secure_string ss = "";
std::cin >> ss;
std::cout << ss;
}
Aucun commentaire:
Enregistrer un commentaire