Namespaces
Variants
Actions

Talk:cpp/io/basic istream/operator gtgt2

From cppreference.com
< Talk:cpp‎ | io

With this change (until C++20)

   template< class CharT, class Traits>
   basic_istream<CharT, Traits>&
       operator>>( basic_istream<CharT, Traits>& st, CharT* s );

to this (since C++20 - relevant part marked in bold)

   template< class CharT, class Traits, std::size_t N >
    basic_istream<CharT, Traits>&
       operator>>( basic_istream<CharT, Traits>& st, CharT (&s)[N] );

I fear I have to modify that piece of code which perfectly worked since the days of C++98

   std::size_t sz = 5;
   char *cp = new char[sz];
   ...
   ... >> std::setw(sz) >> cp

to this:

   ... >> std::setw(sz) >> *reinterpret_cast<char(*)[std::numeric_limits<int>::max()]>(cp)

REALLY?

I hope there is an easier way than to uglify my code with an reinterpret_cast only to "protect" developers who don't understand the array to pointer decay by a fix that forces the use of an array when there are valid reasons to use a pointer.

Link to example: https://godbolt.org/z/q9x7rGqj1

Besides the above with enough context to compile it as source #1 I included another example, still trimmed down but with some practical background(!), where this change SILENTLY(!) breaks code: Up to C++17 the code shown as source #2 had the correct behavior (and I don't see any UB) - which it may have had since 20+ years - and from C++20 it does something differently without giving any notice or warning.

Mwe (talk) 04:20, 16 June 2023 (PDT)

Yeah C++ breaks old code sometimes and it's annoying, but these talk pages aren't for blogging, go complain somewhere appropriate like reddit or twitter or whatever. --Ybab321 (talk) 04:54, 16 June 2023 (PDT)
Sorry, but I was hoping the concentrated knowledge of the experts who might read this could lead to another proposal to solve this, I mean other than to castrate the C++ type checking.

Mwe (talk) 06:37, 16 June 2023 (PDT)

Honestly the change really annoys me too. AFAIK there's no proposal out there to undo this change, nor would I expect there to be one any time in the future. I think the pragmatic solution is to write a little casting function to hide the ugliness of the reinterpret cast. --Ybab321 (talk) 08:02, 16 June 2023 (PDT)
The change was made by P0487R1 (LWG issue 2499). The rationale is "Increase safety via preventing buffer overflow at compile time." (see here) --Xmcgcg (talk) 09:00, 16 June 2023 (PDT)