std::string 第一次分配时不使用自定义分配器

std::string doesn't use custom allocator in first allocation

我想为 basic_string 创建一个自定义分配器,它允许我获得分配的字符串内部数组的所有权。我的具体用例是一个 .NET 互操作场景,其中将字符串编组回托管代码非常昂贵,因为它需要在特定池中分配字符串(至少在 Windows) and more important the ownership of the array in the heap must be transferred. I was able to code such custom allocator for 中并且在主要编译器(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 link):

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++标准是否不要求在所有数据分配中都使用分配器?字符串有特殊的 clause/exception 吗?相同的代码似乎适用于 .

您看到的是短字符串优化 (SSO)。该标准允许 std::string 使用一个小的内部缓冲区构建,字符串可以使用该缓冲区来避免进行任何动态内存分配。这是非常有利的,因为大多数字符串都很小,因此您可以节省大量分配。

遗憾的是,标准中对此缓冲区的大小没有限制。 MSVC 使用 16 个字符,libc++ 使用 22.

这意味着您要么需要确保分配的字符串足够大以使用您的分配器,要么您只需要实现自己的字符串 class。分配足够内存的一个技巧是使用

std::string str;
str.reserve(sizeof(str) + 1);

由于缓冲区是字符串的一部分,如果您要求更多内存那么字符串的大小将不得不动态分配内存。

Is there a special clause/exception for strings? The same code seems to work just fine for std::vector.

std::vector 有一个要求1 移动向量不会使任何 pointers/references/iterators 无效,这意味着它不能有这样的缓冲区。 std::string 没有允许实施 SSO 的要求。

1: Table 71 谈论 X u(rv)X u = rv 并且复杂性要求是 NoteB 其中 NoteB 是 constant所有容器的复杂度,除了 std::array,它具有 线性复杂度