2012-09-26 31 views
0

什麼是C++ 11 ISO標準說一下這樣的表達:constexpr中使用的非常量:標準說的是什麼?

class MyClass 
{ 
    public: 
     constexpr int test() 
     { 
      return _x; 
     } 

    protected: 
     int _x; 
}; 

_x處於constexpr中使用的非const:將它產生錯誤,或將constexpr被簡單地忽略(如當我們傳遞一個非const參數)?

+0

你測試了嗎? –

+0

它不能作爲constexr使用*。 – juanchopanza

+0

@KerrekSB是的,我測試了它。它編譯,但我不知道是否正常。 @juanchopanza當然,但當我有這樣的事情時,問題就會出現:'return(condition)? (const):(非const)' – Vincent

回答

5

這是完全正常的,雖然有點沒用的:

constexpr int n = MyClass().test(); 

由於MyClass是一個聚集,值初始化它好像是會值初始化所有成員,所以這只是零。但隨着一些波蘭這是可以做真正有用的:

class MyClass 
{ 
public: 
    constexpr MyClass() : _x(5) { } 
    constexpr int test() { return _x; } 
// ... 
}; 

constexpr int n = MyClass().test(); // 5 
+0

「*問題當然是這是未定義的行爲,因爲該變量是未初始化的。*」不,它不是 - 你值 - 初始化MyClass的一個實例,所以'MyClass :: _ x'是有保證的爲0.'MyClass m; constexpr int n = m.test();'是UB。 – ildjarn

+0

@ildjarn:你是對的,我忘了沒有用戶定義的構造函數。 –

1

如果表達不解析爲常量表達式,那麼它就不能這樣使用。但它仍然可以使用:

#include <array> 
constexpr int add(int a, int b) 
{ 
    return a+b; 
} 
int main() 
{ 
    std::array<int, add(5,6)> a1; // OK 
    int i=1, 
    int j=10; 
    int k = add(i,j); // OK 
    std::array<int, add(i,j)> a2; // Error! 
} 
相關問題