2013-03-31 88 views
1

我下面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是一個內存管理器我目前正在和變量必須是常量所以一旦它賦予它不可能通過其他類改變。

我該如何解決這個問題?

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

如果我將'minimum_size'轉換爲'uint32&' - 使用舊式轉換 - 然後將值賦給它,是否會在'clang'或'gcc'下編譯? –

+0

@Muhammadalaa:你不能將'uint32'投射到'uint32&'。 – deepmax

+0

像這樣'uint32&minimum_size_ref =(uint32&)minimum_size;',是不是一個有效的代碼? –