I recently read cool article: https://akrzemi1.wordpress.com/2015/08/20/can-you-see-the-bug/ Playing with reduced version on ideone I got surprising behaviour:
#include <iostream>
#include <cassert>
using namespace std;
int main() {
const size_t sz=258;
string s{sz,'#'};
assert(2==s.size());
}
does not compile, but same program with const removed compiles:
#include <iostream>
#include <cassert>
using namespace std;
int main() {
size_t sz=258;
string s{sz,'#'};
assert(2==s.size());
}
So my question is this standard required or just compilers decided that one is a compiler warning and other is an compiler error.
If it helps here are the errors and warnings from gcc 5.1 (tnx godbolt)
!!error: narrowing conversion of '258ul' from 'size_t {aka long unsigned int}' to 'char' inside { }
!!warning: narrowing conversion of 'sz' from 'size_t {aka long unsigned int}' to 'char' inside { } [-Wnarrowing]
good guy clang 3.6 gives error in both cases, but the question remains, is one legal and bad C++ and other illegal C++?
string s{32,32,32};
should just work. But32
is an int and int-to-char is a narrowing conversion. We know that32
can safely be narrowed, precisely because it's a compile-time constant. For this reason compile-time constants are treated differently. (It's not justconst
-const sz = rand()
is not a compile-time constant and might overflow when narrowed) – MSalters Aug 28 '15 at 13:36