C++ error: “taking address of temporary array”

后端 未结 6 1898
渐次进展
渐次进展 2021-01-01 04:42

I am trying to declare an array inside an if-statement. I wrote my code this way so that the object stays in scope once the if-block exits, but now I have a new issue: \"tak

6条回答
  •  Happy的楠姐
    2021-01-01 05:31

    While it is true that the original construct is not valid in C++, standard C++ does have a fairly similar feature: one can create a temporary array using an explicit type name and list-initializer

    using I9 = int [9];
    I9{ 0, 1, 0, 1, -4, 1, 0, 1, 0 };
    

    The above is valid C++ syntax for a temporary array object. But if you try using it in GCC, you will quickly discover that GCC refuses to apply array-to-pointer conversion to such temporary arrays, e.g.

    using C10 = char [10];
    C10 str;
    std::strcpy(str, C10{ 'a', 'b', 'c' });
    // GCC: error: taking address of temporary array
    

    The above is perfectly valid C++, but a bug in GCC prevents it from compiling. Clang and MSVC accept this code.

    In your original code you are actually relying on a GCC extension, which allows you to use C-style compound literal syntax in C++ code, but this extension apparently happens to suffer from the very same bug as described above.

提交回复
热议问题