<stl>将bytes上调至8的倍数

在<<STL源码剖析>>的空间配置一章的二级配置器中,有如下一段源代码,功能是将bytes上调至8的倍数。

enum{_ALIGN=8}; //小型区块的上调边界

private:
static size_t ROUND_UP(size_t bytes){
    return (((bytes)+_ALIGN-1)&~(_ALIGN-1));
}

这里的源码乍一看很难懂,但是十分高效,现在具体看一下实现原理。

这里82^3,二进制表示为00001000。前面的0先省略了,不影响分析。

_ALIGN-1:

00001000->00000111;

~_ALIGN-1:

00000111->11111000;

bytes+ALIGN-1:

x这里如果bytes是8的倍数,那么低3位全是0。

xxxxx000->xxxxx111

(bytes+ALIGN-1)&(~_ALIGN-1):

xxxxx111->xxxxx000

这里得到的是bytes本身。

 

如果bytes不是8的倍数呢?那么首先

8n<bytes<8(n+1)

我们要求的就是8(n+1)。

bytes用二进制表示,低三位不全为0,加上ALIGN-1会向第4位进位。此时将第三位清零,使用取反后相与,得到的就是8(n+1)。

 

这里的简单推导一下:

8n<bytes<8(n+1)

bytes=8n+p,p<8

p存在低3位,8n存在高三位,执行加法bytes+ALIGN-1,产生进位。

现在bytes=8(n+1)+p,清零后为8(n+1)。

 

这个问题还可以推广到将一个数字上调到2^n的倍数。因为2^n的低n位必定全是0,上面是实例n=3的情况。

好的,以下是手动实现这些头文件里所有的STL容器的代码: ``` // iostream namespace mystd { class ostream { public: ostream& operator<<(const char* str) { // 实现输出字符串的逻辑 return *this; } // 其他重载运算符和成员函数 }; static ostream cout; } // memory namespace mystd { template<typename T> class allocator { public: using value_type = T; // 实现分配和释放内存的函数 }; } // stack namespace mystd { template<typename T, typename Container = mystd::vector<T>> class stack { public: using value_type = T; using container_type = Container; // 实现栈的各种函数 }; } // fstream namespace mystd { class filebuf { public: // 实现文件缓冲区相关函数 }; class ifstream { public: ifstream(const char* filename) { // 实现打开文件的逻辑 } // 实现读取文件的逻辑 }; class ofstream { public: ofstream(const char* filename) { // 实现打开文件的逻辑 } // 实现写入文件的逻辑 }; } // vector namespace mystd { template<typename T, typename Allocator = mystd::allocator<T>> class vector { public: using value_type = T; using allocator_type = Allocator; // 实现vector的各种函数 }; } // cmath namespace mystd { double pow(double base, double exponent) { // 实现求幂函数 } // 其他数学函数的实现 } // iomanip namespace mystd { class setprecision { public: setprecision(int n) { // 实现设置输出精度的逻辑 } // 其他重载运算符和成员函数 }; } // exception namespace mystd { class exception { public: virtual const char* what() const noexcept { return "Unknown exception"; } }; } // climits namespace mystd { constexpr int INT_MAX = 2147483647; // 其他常量的定义 } // array namespace mystd { template<typename T, std::size_t N> class array { public: using value_type = T; // 实现数组的各种函数 }; } // cstdint namespace mystd { using int8_t = signed char; using int16_t = short int; using int32_t = int; using int64_t = long long int; // 其他数据类型的定义 } // string namespace mystd { class string { public: // 实现字符串的各种函数 }; } ``` 以上代码只是简单实现了各个STL容器的基本功能,具体实现方式和函数可能会有所不同,仅供参考。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值