c++ - 这是否像 learncpp.com 声称的那样是 GCC 错误?

标签 c++ gcc c-strings compiler-bug

在 C++ 学习网站( https://www.learncpp.com/cpp-tutorial/6-9a-dynamically-allocating-arrays/ )中,有人声称 GCC 在涉及 new 运算符时存在与 C 样式字符串初始化相关的错误:

As of the time of writing, the GCC still has a bug where initializing a dynamically allocated array of chars using a C-style string literal causes a compiler error:

char *array = new char[14] { "Hello, world!" }; // doesn't work in GCC, though it should

我使用的是 GCC 版本 7.4.0。

如果我尝试编译此摘录,我会得到:

error: invalid conversion from ‘const char*’ to ‘char’ [-fpermissive]
     char *array = new char[14] { "Hello, world!" };

如果我尝试编译这样的代码:

char *array = new char[14] {'H', 'e', 'l', 'l', 'o', 0}

然后它就会按预期工作。

我假设这被认为是一个错误,因为:

char array[14]{ "Hello, world!" };

按预期工作。

我找不到这方面的更多信息。有人能确认或否认这是一个 GCC 错误吗?

最佳答案

是的,这是一个 GCC 错误。错误跟踪器中的相关问题是 77841 。引用那边的描述:

5.3.4 New [expr.new] p.17.2
Otherwise, the new-initializer is interpreted according to the initialization rules of 8.5 for direct-initialization.

8.5 Initializers [dcl.init] p.17.1
If the initializer is a (non-parenthesized) braced-init-list, the object or reference is list-initialized (8.5.4).

8.5.4 List-initialization [dcl.init.list] p.3.2
Otherwise, if T is a character array and the initializer list has a single element that is an appropriately-typed string literal (8.5.2), initialization is performed as described in that section.

因此,问题中的 new 表达式应该格式良好,就像数组对象的直接初始化一样。

无法预测何时修复。还是reproducible in GCC's trunk截至撰写本文时。

关于c++ - 这是否像 learncpp.com 声称的那样是 GCC 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60585917/

相关文章:

c - C::B 中的调试器。无法打开 cygwin.S

c - 对 'funtion_name' 的 undefined reference

C++ 在元组中存储原始字符数组

c++ - 我对下面的代码有两个问题

c - printf() 函数如何知道其参数的类型

c++ - 使用构造函数 Vs 动态初始化对象。 C++ 中的新功能?

c++ - 如何在有安全限制的情况下安全地编译和执行c++程序?

c++ - 是否可以保存对shared_ptr 管理的对象的引用?

C++ - 在类上使用 &String[0] 访问 char*

c++ - CMFCCaptionMenuButton 替代品?