用于C++的自定义分配器不用于调用 我正在开发一个基于../p>的C++简单简单的SeCueSyxx字符串实现的自定义分配器。
我的代码编译并执行,如下所示。但是,我注意到我的分配器的allocate、deallocate方法没有得到执行。我错过了什么用于C++的自定义分配器不用于调用 我正在开发一个基于../p>的C++简单简单的SeCueSyxx字符串实现的自定义分配器。,c++,c++11,memory-management,allocator,securestring,C++,C++11,Memory Management,Allocator,Securestring,我的代码编译并执行,如下所示。但是,我注意到我的分配器的allocate、deallocate方法没有得到执行。我错过了什么 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
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> >;
上面的cout语句不产生任何输出。
下面是一个示例用法
{
secure_string ss = "";
std::cin >> ss;
std::cout << ss;
}
小串优化
您看到的是小字符串优化,或者更确切地说,没有看到。。。。尝试分配一个更大的字符串,您将看到您的分配器按预期被调用