c++ - 很难理解 std::basic_string 内存分配

标签 c++ stl stdstring

我目前正在学习 STL,我看到了我的一位老师制作的示例。

template <class T>
struct SpyAllocator : std::allocator<T>
{
typedef T   value_type;

SpyAllocator(/*vector args*/) = default;

template<class U>
SpyAllocator(const SpyAllocator<U>& other){}

template<class U>
struct rebind
{
    using other = SpyAllocator<U>;
};

T*  allocate(std::size_t n)
{
    T* p = (T*) new char[sizeof(T) * n];

    memorySpy.NotifyAlloc(sizeof(T), n, p);
    return p;
};

void    deallocate(T* p, std::size_t n)
{
    memorySpy.NotifyDealloc(p, n);
    delete (char*)p;
}

typedef T*          pointer;
typedef const T*    const_pointer;
typedef T&          reference;
typedef const T&    const_reference;
};

template <class T, class U>
bool    operator==(const SpyAllocator<T>&, const SpyAllocator<U>&) { return 
false; }

template <class T, class U>
bool    operator!=(const SpyAllocator<T>&, const SpyAllocator<U>&) { return 
false; }

上面是他的分配器实现。

#define String      std::basic_string<char, std::char_traits<char>, SpyAllocator<char>>

他将std::basic_string定义为String

在main.cpp文件中,

int main()
{
    DO(String s1 = "Bonjour");
    DO(String s2 = " le monde !");
    DO(String s3 = s1 + s2);
    printf("s3 : %s\n", s3.c_str());

    printf("\nDestroy vector\n\n");
    return 0;
}

他正在测试+运算符和拷贝构造函数,结果是

String s1 = "Bonjour"

String s2 = " le monde !"

String s3 = s1 + s2
*** Allocate block 1 : 31 elem of 1 bytes

s3 : Bonjour le monde !

Destroy vector

*** Deallocate block 1 : 31 elem of 1 bytes

我的问题是:

1- 我统计了String s1String s2的字符数(包括\0),是19个,但是分配了31个。 分配 block 1:1 个字节的 31 个元素

这背后的原因是什么?

2- 似乎 String s1String s2 构造函数没有分配任何内存,但 String s1String s2 仍然具有值(value)。

这怎么可能?

感谢您的宝贵时间!

最佳答案

这是我们在查看 STDLib

basic_string.h 时得到的结果
enum
{
    _S_local_capacity = 15 / sizeof(_CharT)
};

union
{
    _CharT _M_local_buf[_S_local_capacity + 1];
    size_type _M_allocated_capacity;
};

We know that std::string is a typedef for a specialization of a std::basic_string with char type.

basic_string contains a 15 bytes fixed buffer for short strings then we +1 for the \0.因此,当我们连接存储在小缓冲区中的 2 个字符串时,它将连接整个字符串,然后为 \0 添加 +1。所以它将是 15 + 15 + 1 = 31。

这是我阅读basic_string.h后的理解

关于c++ - 很难理解 std::basic_string 内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47063130/

相关文章:

python - 尝试编译 Yolo 时,出现找不到包错误

c++ - 如何将 vector 保存到二进制文件?

c++ - std::sort 不适用于重载 < 运算符的用户定义对象

c++ - 如何将 vector 中 pair 的第一个元素复制到另一个 vector ?

c++ - 如何计算 std::basic_string<TCHAR>

c++ - 遍历对列表,列表在数组中

c++ - 有没有一种方法可以将std::string转换为c++中的vector <char>?

c++ - 使用 EnumFontFamiliesEx 函数枚举时字体过多

c++ - 为什么这个内联汇编中的 ror op 不能正常工作?