最近我发现一件事就程序风格和性格也有关系
比如说我就是绥靖和治标派
1.绥靖派
例子:
std::vector<int> _vec_int;
int _max_index;
int _cur_index;
void init()
{
_max_index = 10;
_vec_int.reset(_max_index);
}
void add(const int num)
{
if (_cur_index == _max_index - 1)
{
break;
}
_vec_int[_cur_index] = num;
++cur_index;
}
初始化一个数组,当数组越界时执行add函数,我喜欢直接break,不进行任何操作。
实际上更激进的做法是,assert,在debug模式下,直接崩溃,就能定位到数组越界
std::vector<int> _vec_int;
int _max_index;
int _cur_index;
void init()
{
_max_index = 10;
_vec_int.reset(_max_index);
}
void add(const int num)
{
assert(_cur_index < _max_index);
_vec_int[_cur_index] = num;
++cur_index;
}
第二点是治标派
例如下代码,本来我的模块需要size大小的共享内存来进行进程通信,不过下端模块把我的size大小分为了8个部分,这样我的可用大小为 size/8 ,不符合我模块邀请,我的该变方法为 将用户传入的size * 8,此乃治标不治本的方法,如下端模块变动,将又会影响我的模块。
// 我的模块
class me
{
// [in] size 初始化一块共享内存,大小为size
void init_me(int size)
{
_other.init_other(size);
}
other _other;
}
// 他人模块
class other
{
// 初始化 size的共享内存
void init_other(int size)
{
int n = 2;
while (n < size / 8)
{
n *= 2;
}
_size = n;
}
int _size;
}