使用额外检查初始化const变量

时间:2013-03-31 16:10:20

标签: c++ initialization const initializer-list

我有以下struct

// options for pool_base-based pools
struct pool_options
{
    // pool initial_size
    const uint32 initial_size;

    // can pool grow?
    const bool can_grow;
    // if minimum free space by percent?
    // true for percentage size, false for fixed-amount-of-bytes minimum.
    const bool min_by_percent;
    // minimum value.
    const uint32 minimum_size;
    // is growth by percentage?
    // true for percentage size, false for fixed-amount-of-bytes growth.
    const bool grow_by_percent;
    // growth value.
    const uint32 grow_size;

    // true to prevent manager from free up extra space.
    const bool keep_extra_space;
    // is shrinkage by percent?
    // true for percentage size, false for fixed-amount-of-bytes shrinkage.
    const bool max_by_percent;
    // maximum value.
    const uint32 maximum_size;

    // is defragment occur by percent?
    // true for percentage defragment, false for fixed-amount-of-bytes defragment.
    //
    // if percentage of fragmented memory from total memory occur then defragment take place.
    const bool defrag_by_percent;
    // fragment size
    const uint32 fragment_size;
};

我将初始化构造函数初始化列表中的常量,但问题是我需要进行额外的检查以验证输入值,但这会导致编译器发出l-value specifies const object错误信号。构造函数的代码:

pool_options(uint32 is, bool cg, bool mip, uint32 mis, bool gp, uint32 gs, bool kes, bool map, uint32 mas, bool dp, uint32 fs)
    : initial_size(is), can_grow(cg), min_by_percent(mip), minimum_size(mis), grow_by_percent(gp),
      grow_size(gs), keep_extra_space(kes), max_by_percent(map), maximum_size(mas), defrag_by_percent(dp), fragment_size(fs)
{
    if (can_grow)
    {
        if (min_by_percent && minimum_size > 100) minimum_size = 100;
        if (grow_by_percent && grow_size > 100) grow_size = 100;
    }
    else
    {
        min_by_percent = false;
        minimum_size = 0;
        grow_by_percent = false;
        grow_size = 0;
    }

    if (keep_extra_space)
    {
        max_by_percent = false;
        maximum_size = 0;
    }
    else
    {
        if (max_by_percent && maximum_size > 100) maximum_size = 100;
    }

    if (defrag_by_percent)
    {
        if (fragment_size > 100) fragment_size = 100;
    }

}

struct用于我当前正在处理的内存管理器,并且变量必须是常量,因此一旦分配它就永远不会被其他类更改。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

您可以使用检查器成员函数,例如:

struct Test
{
    const int x;

    Test(int x) : x(checkX(x)) // <--------- check the value
    {
       std::cout << this->x << std::endl;
    }

private:

    int checkX(int x) const
    {
        if (x < 0 || x > 100)
            return 0;
        else
            return x;
    }
};

int main()
{
    Test t(-10);
}