【发布时间】:2020-03-27 13:12:30
【问题描述】:
我想为basic_string 创建一个自定义分配器,它允许我获得分配的字符串内部数组的所有权。我的具体用例是 .NET 互操作场景,其中将字符串封送回托管代码的成本很高,因为它需要在特定池中分配字符串(至少在 Windows 中),更重要的是堆中数组的所有权必须转移。我能够为std::vector 编写这样的自定义分配器,并成功验证了主要编译器(MSVC、gcc、clang)的兼容性。我现在尝试对basic_string 使用相同的分配器,并且我观察到奇怪的行为,因为所有主要的 STL 实现似乎都没有将提供的分配器用于第一次分配,通常是前 16 个字节。它遵循我正在使用的代码:
#include <memory>
#include <stdexcept>
#include <vector>
#include <iostream>
// The requirements for the allocator where taken from Howard Hinnant tutorial:
// https://howardhinnant.github.io/allocator_boilerplate.html
template <typename T>
struct MyAllocation
{
size_t Size = 0;
std::unique_ptr<T> Ptr;
MyAllocation() { }
MyAllocation(MyAllocation && other) noexcept
: Ptr(std::move(other.Ptr)), Size(other.Size)
{
other.Size = 0;
}
};
// This allocator keep ownership of the last allocate(n)
template <typename T>
class MyAllocator
{
public:
using value_type = T;
private:
// This is the actual allocator class that will be shared
struct Allocator
{
[[nodiscard]] T* allocate(std::size_t n)
{
T *ret = new T[n];
if (!(Current.Ptr == nullptr || CurrentDeallocated))
{
// Actually release the ownership of the Current unique pointer
Current.Ptr.release();
}
Current.Ptr.reset(ret);
Current.Size = n;
CurrentDeallocated = false;
return ret;
}
void deallocate(T* p, std::size_t n)
{
(void)n;
if (Current.Ptr.get() == p)
{
CurrentDeallocated = true;
return;
}
delete[] p;
}
MyAllocation<T> Current;
bool CurrentDeallocated = false;
};
public:
MyAllocator()
: m_allocator(std::make_shared<Allocator>())
{
std::cout << "MyAllocator()" << std::endl;
}
template<class U>
MyAllocator(const MyAllocator<U> &rhs) noexcept
{
std::cout << "MyAllocator(const MyAllocator<U> &rhs)" << std::endl;
// Just assume it's a allocator of the same type. This is needed in
// MSVC STL library because of debug proxy allocators
// https://github.com/microsoft/STL/blob/master/stl/inc/vector
m_allocator = reinterpret_cast<const MyAllocator<T> &>(rhs).m_allocator;
}
MyAllocator(const MyAllocator &rhs) noexcept
: m_allocator(rhs.m_allocator)
{
std::cout << "MyAllocator(const MyAllocator &rhs)" << std::endl;
}
public:
T* allocate(std::size_t n)
{
std::cout << "allocate(" << n << ")" << std::endl;
return m_allocator->allocate(n);
}
void deallocate(T* p, std::size_t n)
{
std::cout << "deallocate(\"" << p << "\", " << n << ")" << std::endl;
return m_allocator->deallocate(p, n);
}
MyAllocation<T> release()
{
if (!m_allocator->CurrentDeallocated)
throw std::runtime_error("Can't release the ownership if the current pointer has not been deallocated by the container");
return std::move(m_allocator->Current);
}
public:
// This is the instance of the allocator that will be shared
std::shared_ptr<Allocator> m_allocator;
};
// We assume allocators of different types are never compatible
template <class T, class U>
bool operator==(const MyAllocator<T>&, const MyAllocator<U>&) { return false; }
// We assume allocators of different types are never compatible
template <class T, class U>
bool operator!=(const MyAllocator<T>&, const MyAllocator<U>&) { return true; }
int main()
{
std::cout << "Test MyAllocator<char>" << std::endl;
using MyString = std::basic_string<char, std::char_traits<char>, MyAllocator<char>>;
MyAllocator<char> allocator;
MyString str(allocator);
str = "0123456789ABCDE"; // 16 bytes including null termination. No use of the allocator
// str = "0123456789ABCDEF"; // 17 bytes including null termination. Here the allocator is used,
// tipically doubling the space required
}
代码的输出如下,显示没有使用分配器。在 MSVC、clang 和 gcc 中类似(Wandbox 链接):
Test MyAllocator<char>
MyAllocator()
MyAllocator(const MyAllocator &rhs)
相反,如果我有一个需要超过 16 个字节的分配,例如我的代码中的注释行,则 gcc 中的输出是这样的(在 MSVC 中具有类似的输出,在 clang 中需要 >= 24 个字节):
Test MyAllocator<char>
MyAllocator()
MyAllocator(const MyAllocator &rhs)
allocate(31)
deallocate("0123456789ABCDEF", 31)
这显示了所有 STL 实现之间的共同模式,因为它们似乎只是忽略了小字符串分配器的使用,作为一种优化。可悲的是,库开发人员并没有做到这一点,因为他们可以像我一样将任何行为封装在字符串的自定义分配器中,可能会在分支中浪费 CPU 周期(可能还有存储空间)。问题如下:C++ 标准是否不需要在所有数据分配中使用分配器?字符串是否有特殊条款/例外?对于std::vector,相同的代码似乎也能正常工作。
【问题讨论】:
-
小字符串优化再次来袭!
标签: c++ stl char stdstring allocator