gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 04:19:38 25 4
gpt4 key购买 nike

我有以下结构:

// 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 specified 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 用于我目前正在使用的内存管理器,变量必须是常量,因此一旦分配,它就永远不会被其他类更改。

我该如何解决这个问题?

最佳答案

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

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);
}

关于c++ - 使用额外检查初始化 const 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15731462/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com