c++ 中的自定义分配器,用于不调用secure_string实现
Custom allocator in c++ for secure_string implementation not getting invoked
我正在开发一个自定义分配器,用于基于 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;
}
小字符串优化
您看到的是小字符串优化(或者更确切地说,可能看不到......尝试分配一个更大的字符串,您将看到您的分配器按预期被调用。
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 函数调用中参数的顺序重要吗
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 在c++类上调用void函数
- 为什么 std::unique 不调用 std::sort?
- 调用专用模板时出错"no matching function for call to [...]"
- 选择要调用的构造函数
- C++为什么尽管我调用了void函数,它却不起作用
- 构造函数正在调用一个使用当前类类型的函数
- 变量没有改变?通过向量的函数调用
- 没有为自己的结构调用列表推回方法
- 调用'begin(int [n])'没有匹配函数
- 什么时候调用析构函数
- 如何用参数值调用函数(仅在运行时已知)
- std::cout.imbue()多重调用
- 如何禁用SCL SECURE WARNING仅为一个函数调用,而不是全局