[英]undefined reference to class static constexpr struct, g++ vs clang
[英]G++ vs Clang : inconsistent behavior for constexpr and const
考慮以下代碼:
constexpr const int A = 42;
const int &B = A;
static_assert(&A == &B, "Bug");
constexpr const int &C = B;
static_assert(&A == &C, "Bug");
int main() { return 0; }
它被clang版本3.3完全接受,而g ++(SUSE Linux)4.8.1 20130909 [gcc-4_8-branch版本202388拒絕使用以下命令:
bug2.cpp:5:1: error: non-constant condition for static assertion
static_assert(&A == &B, "Bug");
^
bug2.cpp:5:1: error: the value of ‘B’ is not usable in a constant expression
bug2.cpp:2:12: note: ‘B’ was not declared ‘constexpr’
const int &B = A;
^
在我看來,GCC是正確的(而我當然更喜歡clang行為)。 嘗試閱讀標准時,我意識到我還沒有足夠的語言律師來決定。 誰能確認?
the value of 'B' is not usable in a constant expression
是不正確的。 您沒有在B上執行從左值到右值的轉換,這是“值”的通常含義。 您僅使用其地址。 唯一相關的常量表達式規則禁止:
引用引用類型的變量或數據成員的id表達式,除非引用具有先前的初始化,且使用常量表達式初始化;
但是, B
確實對參考常量表達式進行了初始化。
引用常量表達式是左值核心常量表達式,用於指定具有靜態存儲持續時間或函數的對象。
在這種情況下, B
的初始值設定項是A
,它的常數要盡可能大。 A
和B
靜態引用相同的對象。
因此,這是一個GCC錯誤。
如果您不是語言律師,則通常不能將引用用作常量表達式,只能使用值(如果有例外,請糾正我)。 從這個意義上講,最接近您的代碼的有效值為:
constexpr int A = 42;
constexpr int B = A;
static_assert(A == B, "Bug");
但是,就我而言,Clang 3.3和GCC 4.8.1都會在您的代碼上出現預期的錯誤。
編輯顯然,我的知識仍然有點狹窄,對不起。 根據鏈接的不同,可能會有一些例外情況,例如,如果語句是全局的,則在main()
之外接受( 實時 )代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.