簡體   English   中英

編譯器生成具有 constexpr 混淆行為的默認構造函數

[英]Compiler generated default constructor with constexpr confusing behavior

樣品 1

template <typename T>
struct A
{

    constexpr A() = default;
    T x;
};

int main(){
    static_assert(A<int>{}.x == int{}, "FAILED");
}

樣品 2

struct A
{
    constexpr A() = default;
    int x;
};

int main(){
    static_assert(A{}.x == int{}, "Not Equal");
}

我對第一個示例如何編譯和傳遞 static 斷言感到困惑,而第二個示例無法編譯,如constexpr 默認構造函數中所述, Error: defaulted definition of default constructor is not constexpr

嘗試閱讀以下內容,但無法理解第一個是如何工作的,而另一個則不是。 http://eel.is/c++draft/class.ctor#class.default.ctor-4

默認構造函數默認且未定義為已刪除的默認構造函數在使用 odr ([basic.def.odr]) 創建其 class 類型 ([intro.object]) 的 object 時隱式定義常量求值([expr.const]),或者在第一次聲明后顯式默認。 隱式定義的默認構造函數執行 class 的一組初始化,這將由用戶編寫的 class 的默認構造函數執行,沒有 ctor-initializer 和空的復合語句。 如果該用戶編寫的默認構造函數格式不正確,則程序格式錯誤。 如果該用戶編寫的默認構造函數滿足 constexpr 構造函數 ([dcl.constexpr]) 的要求,則隱式定義的默認構造函數是 constexpr。 在隱式定義 class 的默認默認構造函數之前,隱式定義其基類及其非靜態數據成員的所有非用戶提供的默認構造函數。 [注意:隱式聲明的默認構造函數具有異常規范([except.spec])。 顯式默認定義可能具有隱式異常規范,請參閱 [dcl.fct.def]。 ——尾注]

謝謝你!

以下內容可以說明這個問題:

int main(){
    constexpr A<int> a;
}

嘗試調用constexpr構造函數會產生此錯誤 (gcc):

<source>: In function 'int main()':
<source>:12:22: error: uninitialized 'const a' [-fpermissive]
   12 |     constexpr A<int> a;
      |                      ^
<source>:4:8: note: 'const struct A<int>' has no user-provided default constructor
    4 | struct A
      |        ^
<source>:7:15: note: constructor is not user-provided because it is explicitly defaulted in the class body
    7 |     constexpr A() = default;
      |               ^
<source>:8:7: note: and the implicitly-defined constructor does not initialize 'int A<int>::x'
    8 |     T x;
      |       ^

但是,如果我沒有遺漏任何東西,那么constexpr構造函數應該已經是一個錯誤,因為它不能是constexpr (請參見此處)。

gcc 和 clang 都接受您的代碼,但在嘗試調用constexpr構造函數時都會產生錯誤。 我想這是一個編譯器錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM