C ++中用于调用secure_string实现的自定义分配器

问题描述 投票:0回答:1

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

我的代码,如下所示,进行编译和执行。但是,我注意到分配器的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_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;
    }
c++ c++11 memory-management allocator securestring
1个回答
1
投票

小字符串优化

您正在看到小字符串优化(或者也许没有看到……)。尝试分配一个更大的字符串,您将看到您的分配器按预期被调用。

© www.soinside.com 2019 - 2024. All rights reserved.