vendredi 28 août 2015

Is it standard behaviour that adding const to size_t can cause compile failure?

I recently read cool article: http://ift.tt/1EFN2JN 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)

!!warning: narrowing conversion of 'sz' from 'size_t {aka long unsigned int}' to 'char' inside { } [-Wnarrowing]

!!error: narrowing conversion of '258ul' from 'size_t {aka long unsigned int}' to 'char' inside { }

good guy clang 3.6 gives error in both cases, but the question remains, is one legal and bad C++ and other illegal C++?

Aucun commentaire:

Enregistrer un commentaire