C++ 难以理解std::basic_字符串内存分配
我目前正在学习STL,我遇到了一位老师的例子C++ 难以理解std::basic_字符串内存分配,c++,stl,stdstring,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){} templat
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; }
他正在测试+运算符和复制构造函数,结果是
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-我已经计算了字符串s1
和字符串s2
的字符数(包括\0),是19个。但分配了31个<代码>分配块1:31个1字节的元素
这背后的原因是什么
2-似乎字符串s1
和字符串s2
构造函数没有分配任何内存,但是字符串s1
和字符串s2
仍然具有该值
怎么可能呢
谢谢你抽出时间 这里是我们在查看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;
};
因此,当我们连接存储在小缓冲区中的2个字符串时,它将连接整个字符串,然后为\0
添加+1。所以它将是15+15+1=31
这就是我通过阅读
basic_string.h
了解到的,这里是我们在看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;
};
因此,当我们连接存储在小缓冲区中的2个字符串时,它将连接整个字符串,然后为\0
添加+1。所以它将是15+15+1=31
这是我从阅读
basic_string.h
#define string…
中了解到的,真是个坏主意。不要为此使用预处理器,请使用类型别名:using String=…
(只需将#define String
更改为using String=
即可满足您的所有需要)@Justin,谢谢您的评论,我会记住的。但它是由我的一位老师制作的。“…没有分配任何内存…”查找:“小字符串优化”(小字符串直接分配到std::string类中,而不是通过分配器分配到堆上)。此外,字符串(和向量)有时可以按所需空间的倍数增长。(1.6和2是常见的倍数)我认为你的老师犯了一个错误,因为他将new[]
与delete
配对,这是UB。谢谢@Richard criten!我从昨天起就一直在讨论这个问题,不知道背后的原因。你刚刚救了我一天<代码>#定义字符串…真是个坏主意。不要为此使用预处理器,请使用类型别名:using String=…
(只需将#define String
更改为using String=
即可满足您的所有需要)@Justin,谢谢您的评论,我会记住的。但它是由我的一位老师制作的。“…没有分配任何内存…”查找:“小字符串优化”(小字符串直接分配到std::string类中,而不是通过分配器分配到堆上)。此外,字符串(和向量)有时可以按所需空间的倍数增长。(1.6和2是常见的倍数)我认为你的老师犯了一个错误,因为他将new[]
与delete
配对,这是UB。谢谢@Richard criten!我从昨天起就一直在讨论这个问题,不知道背后的原因。你刚刚救了我一天!谢谢你的澄清!谢谢你的澄清!
enum
{
_S_local_capacity = 15 / sizeof(_CharT)
};
union
{
_CharT _M_local_buf[_S_local_capacity + 1];
size_type _M_allocated_capacity;
};