Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected result from std::wstring::resize_and_overwrite

Tags:

c++

this program

#include <iostream>
#include <string>


int main()
{
    std::wstring ws;
    for(unsigned i=1;i<64;++i){
        std::cout<<i<<' ';
        ws.resize_and_overwrite(i,[](wchar_t*s,size_t c){std::cout<<c<<'\n';return 0;});
    }

    return 0;
}

outputs

1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 14
9 9
10 10
11 11
12 12
13 13
14 14
15 28
16 16
17 17
18 18
19 19
20 20
21 21
22 22
23 23
24 24
25 25
26 26
27 27
28 28
29 56
30 30
31 31
32 32
33 33
34 34
35 35
36 36
37 37
38 38
39 39
40 40
41 41
42 42
43 43
44 44
45 45
46 46
47 47
48 48
49 49
50 50
51 51
52 52
53 53
54 54
55 55
56 56
57 112
58 58
59 59
60 60
61 61
62 62
63 63

However, according to the doc https://en.cppreference.com/w/cpp/string/basic_string/resize_and_overwrite, 2. Evaluates std::move(op)(p, count).

the values of i and c should always be the same. What is wrong with the code, did I miss something? I guess there must be some undefined behavior at work. The output in https://godbolt.org/ is not the same as that of my PC, but i and c are still different in some iterations.

like image 443
user42471 Avatar asked Feb 28 '26 17:02

user42471


1 Answers

Your program has well-defined behavior and should always produce equal values on each line according to the current C++23 draft.

The behavior you see is due to libstdc++ being non-conforming to the current C++23 draft. A bug report for this already exists here.

As stated in the bug report, the intention (which seems reasonable to me) might have been that the user-callable is (at least sometimes) given information about the actual size of the allocation that way, so that it can potentially use that extra space that is already allocated. However, this is not conforming to the standard draft. I don't know whether Jonathan Wakely intents to make libstdc++ conforming or instead to propose adapting the standard. I didn't find any matching open LWG issue at https://cplusplus.github.io/LWG/lwg-index.html.

like image 92
user17732522 Avatar answered Mar 02 '26 06:03

user17732522