2 回答

TA貢獻1877條經驗 獲得超1個贊
在libc中++實現有點復雜,我會忽略它的替代性設計,并假設小端計算機:
template <...>
class basic_string {
/* many many things */
struct __long
{
size_type __cap_;
size_type __size_;
pointer __data_;
};
enum {__short_mask = 0x01};
enum {__long_mask = 0x1ul};
enum {__min_cap = (sizeof(__long) - 1)/sizeof(value_type) > 2 ?
(sizeof(__long) - 1)/sizeof(value_type) : 2};
struct __short
{
union
{
unsigned char __size_;
value_type __lx;
};
value_type __data_[__min_cap];
};
union __ulx{__long __lx; __short __lxx;};
enum {__n_words = sizeof(__ulx) / sizeof(size_type)};
struct __raw
{
size_type __words[__n_words];
};
struct __rep
{
union
{
__long __l;
__short __s;
__raw __r;
};
};
__compressed_pair<__rep, allocator_type> __r_;
}; // basic_string
注意:__compressed_pair基本上是針對空基優化而優化的一對,又稱template <T1, T2> struct __compressed_pair: T1, T2 {};; 對于所有意圖和目的,你可以認為它是一個常規對。它的重要性剛剛出現,因為它std::allocator是無國籍的,因此是空的。
好的,這是相當原始的,所以讓我們檢查一下這些機制!在內部,許多函數將調用__get_pointer()自己調用__is_long以確定字符串是否使用__long或__short表示:
bool __is_long() const _NOEXCEPT
{ return bool(__r_.first().__s.__size_ & __short_mask); }
// __r_.first() -> __rep const&
// .__s -> __short const&
// .__size_ -> unsigned char
說實話,我不太確定這是標準C ++(我知道最初的子序列規定,union但不知道它是如何與匿名聯合和別名一起拋出的),但是允許標準庫利用定義的實現無論如何。
- 2 回答
- 0 關注
- 670 瀏覽
添加回答
舉報