c++ 中的自定义分配器,用于不调用secure_string实现

Custom allocator in c++ for secure_string implementation not getting invoked

本文关键字:secure 调用 string 实现 用于 自定义 分配器 c++      更新时间:2023-10-16

我正在开发一个自定义分配器,用于基于 https://en.cppreference.com/w/cpp/named_req/Allocator 的 c++ 中简单而基本的secure_string实现。

我的代码(如下所示(编译并执行。但是,我注意到我的分配器的分配、解除分配方法没有得到执行。我错过了什么?

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  << " bytesn";
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 buffern";
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> >;

上面的 cout 语句不会产生任何输出。 下面是一个用法示例

{
secure_string ss = "";
std::cin >> ss;
std::cout << ss;
}

小字符串优化

您看到的是小字符串优化(或者更确切地说,可能看不到......尝试分配一个更大的字符串,您将看到您的分配器按预期被调用。