gpt4 book ai didi

c++ - 当我聚合初始化一个数组而 gcc 没有时,Clang 警告我

转载 作者:搜寻专家 更新时间:2023-10-31 02:21:51 24 4
gpt4 key购买 nike

当我用 CLANG 编译以下代码时:

#include <iostream>
#include <array>
#include <algorithm>
#include <functional>

int main() {
std::array<int, 2> a = {1, 2};
std::array<int, 2> b = {2, 1};
std::array<int, 2> c;
std::transform(a.begin(), a.end(), b.begin(), c.begin(), std::multiplies<int>());
for(auto &&i : c) std::cout << i << " ";
std::cout << std::endl;
}

通过发出命令:

clang++ -std=c++14 -O2 -Wall -pedantic -pthread main.cpp

它发出警告:

warning: suggest braces around initialization of subobject [-Wmissing-braces]

CLANG DEMO

但是,GCC 编译这个程序时根本没有发出警告。

GCC DEMO

问:

  1. 哪个编译器是正确的?
  2. Clangs 警告我的原因是什么?

最佳答案

在某些情况下,大括号可以省略。这是其中一个案例。用于初始化 ab 的最外层大括号是可选的。无论哪种方式在语法上都是正确的——但只包含它们会更清楚。 Clang 只是就此警告您(警告,而非错误)——这是一个完全有效的警告。而作为 chris , 指出,对于 -Wmissing-braces,gcc 会发出相同的警告。最终,两个编译器都接受了正确的代码;它毕竟是一个有效的程序。这才是最重要的。

来自 [dcl.init.aggr]:

Braces can be elided in an initializer-list as follows. If the initializer-list begins with a left brace, then the succeeding comma-separated list of initializer-clauses initializes the members of a subaggregate; it is erroneous for there to be more initializer-clauses than members. If, however, the initializer-list for a subaggregate does not begin with a left brace, then only enough initializer-clauses from the list are taken to initialize the members of the subaggregate; any remaining initializer-clauses are left to initialize the next member of the aggregate of which the current subaggregate is a member. [ Example:

float y[4][3] = {
{ 1, 3, 5 },
{ 2, 4, 6 },
{ 3, 5, 7 },
};

is a completely-braced initialization: 1, 3, and 5 initialize the first row of the array y[0], namely y[0][0], y[0][1], and y[0][2]. Likewise the next two lines initialize y[1] and y[2]. The initializer ends early and therefore y[3]s elements are initialized as if explicitly initialized with an expression of the form float(), that is, are initialized with 0.0. In the following example, braces in the initializer-list are elided; however the initializer-list has the same effect as the completely-braced initializer-list of the above example,

float y[4][3] = {
1, 3, 5, 2, 4, 6, 3, 5, 7
};

The initializer for y begins with a left brace, but the one for y[0] does not, therefore three elements from the list are used. Likewise the next three are taken successively for y[1] and y[2]. —end example ]

关于c++ - 当我聚合初始化一个数组而 gcc 没有时,Clang 警告我,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30959915/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com