赞
踩
目录
- union _Bxty
- { // storage for small buffer or pointer to larger one
- value_type _Buf[_BUF_SIZE];
- pointer _Ptr;
- char _Alias[_BUF_SIZE]; // to permit aliasing
- } _Bx;
- 大多数情况下字符串的长度都小于16,当string对象创建好之后,内部已经有了16个字符数组的固定空间,不需要通过堆创建,效率高。
- 还有一个size_t字段保存字符串长度,一个size_t字段保存从堆上开辟空间总的容量
- 还有一个指针做一些其他事情。
- 故总共占16+4+4+4=28个字节。
- struct _Rep_base
- {
- size_type _M_length;
- size_type _M_capacity;
- _Atomic_word _M_refcount;
- };
- private:
- char* _str = nullptr;
- size_t _size = 0;
- size_t _capacity = 0;
- // 为了和标准库区分,此处使用String
- class String
- {
- public:
-
- /*String()
- :_str(new char[1])
- {*_str = '\0';}
- */
- //String(const char* str = "\0") 错误示范
- //String(const char* str = nullptr) 错误示范
- String(const char* str = "")//默认包含 \0
- {
- // 构造String类对象时,如果传递nullptr指针,可以认为程序非法
- if (nullptr == str)
- {
- assert(false);
- return;
- }
- _str = new char[strlen(str) + 1];
- strcpy(_str, str);
- }
- ~String()
- {
- if (_str)
- {
- delete[] _str;
- _str = nullptr;
- }
- }
- private:
- char* _str;
- };
- // 测试
- void TestString()
- {
- String s1("hello bit!!!");
- String s2(s1);
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。