2012-12-25 63 views
2

某些編譯器支持pure and const,但請檢查這些斷言是否有效?例如:C++編譯時間檢查副作用

int global_value = 42; 
const int global_value_const = 42; 

int MyPureFunction __attribute__ ((pure_check?)) (
    int input, 
    int* input_ptr, 
    const int* input_const_ptr, 
    int foo& input_ref, 
    const int& input_const_ref) 
{ 
    int temporary = input; // Valid, can read local but mutable state. 

    global_value += temporary;  // Invalid, cannot mutate external state 
    temporary += global_value;  // Invalid, cannot read non-const global data. 
    temporary += global_value_const; // Valid, can read const global data. 

    temporary += *input_ptr;  // Invalid, cannot derefernece non-const ptr. 
    temporary += *input_const_ptr; // Valid, can dereference a const ptr. 
    temporary += input_ref;   // Invalid, cannot use non-const reference. 
    temporary += foo->value;  // Valid, can reference a const reference. 

    return temporary;  // Valid., if all invalid statements above are removed... 
} 
+0

一個'constexpr'將_pure_,雖然它不是一個_pure_功能 –

+0

更受限制。如果我是用這個,也只有一個足夠了(我可以使用一系列函數,就像monad中的綁定操作一樣),但其他人會使用它,這對他們來說太複雜了。我需要它是一個很好的常規多語句函數。 – Jonathan

回答

5

做任何要約,以檢查這些斷言持有

有跡象表明,實施效果的推斷或影響打字沒有C++編譯器,所以只能臨時檢查純度會得到支持, 最好。

有關影響打字的背景下,我建議本Lippmeier的博士論文,Type Inference and Optimisation for an Impure World