【问题标题】:std::string doesn't use custom allocator in first allocationstd::string 在第一次分配中不使用自定义分配器
【发布时间】: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


【解决方案1】:

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

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

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

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

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

字符串有特殊条款/例外吗?对于std::vector,相同的代码似乎也能正常工作。

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

1:Table 71 谈论X u(rv)X u = rv,复杂度要求是NoteB,其中NoteB 是恒定复杂度 对于除std::array 之外的所有容器,它具有线性复杂度

【讨论】:

  • “酷”,我猜。是否有 C++ 标准规范参考,我可以安全地使用我的分配器至少用于std::vector?我很有可能在我的 .NET 编组场景中使用它,因为字符串只是字符数组,我只需要在 UTF-8 -> UTF-16 转换期间附加逻辑。
  • @ceztko Table 71 具有 X u(rv); 复杂度注释 B,其中 NoteB恒定复杂度。这意味着不能有缓冲区,因为这需要复制/移动并且是线性的。 std::string 没有这个要求。
  • 这有点微妙,但理论上 16/22 字节或任何常数仍然是常数复杂性,因为它并不真正依赖于用户数据。
  • @ceztko 复杂性与操作本身有关。移动 SSO 字符串将花费您 O(N) 个字符副本。移动 std::vector 始终是 O(1),因为没有复制或移动任何元素。
  • 好!如果您可以添加最后的规范性参考来回答,谢谢。立即 +1。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-28
  • 2014-02-01
  • 2020-11-04
相关资源
最近更新 更多