Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MSVC accepts std::string array initialized with string literal but gcc and clang rejects

I noticed that msvc with C++20 allows a std::string array to be initialized by a string literal but both gcc and clang rejects it. Demo

#include <string>
int main()
{ 
       std::string a[] = "a";   //msvc c++20 accepts while msvc c++17 rejects and gcc and clang all versions rejects this 
}  

What should be the correct behavior here according to the C++ standard.


1 Answers

This is CWG2824 that points out that the program should be ill-formed but the current wording(which was introduced through P0960R3) makes it well-formed.

Currently the wording in dcl.init.general#16.5 says:

Otherwise, if the destination type is an array, the object is initialized as follows. Let x1, . . . , xk be the elements of the expression-list. If the destination type is an array of unknown bound, it is defined as having k elements. Let n denote the array size after this potential adjustment. If k is greater than n, the program is ill-formed. Otherwise, the ith array element is copy-initialized with xi for each 1 ≤ i ≤ k, and value-initialized for each k < i ≤ n. For each 1 ≤ i < j ≤ n, every value computation and side effect associated with the initialization of the ith element of the array is sequenced before those associated with the initialization of the jth element.


While the correct/amended wording(as suggested in the CWG2824) is:

Otherwise, if the destination type is an array, the object is initialized as follows. The initializer shall be of the form ( expression-list ). Let x1, . . . , xk be the elements of the expression-list. If the destination type is an array of unknown bound, it is defined as having k elements. Let n denote the array size after this potential adjustment. If k is greater than n, the program is ill-formed. Otherwise, the ith array element is copy-initialized with xi for each 1 ≤ i ≤ k, and value-initialized for each k < i ≤ n. For each 1 ≤ i < j ≤ n, every value computation and side effect associated with the initialization of the ith element of the array is sequenced before those associated with the initialization of the jth element.

Note the emphasized part in the above sentence which makes the code ill-formed.


Note that P0960 introduced the change in wording in dcl.init.general in C++20 only. That is, the defect report is for C++20 and onwards. For C++17 there is no need for any change in the wording because dcl.init#17.5 already makes the program ill-formed.

like image 74
Anoop Rana Avatar answered Sep 07 '25 21:09

Anoop Rana