Debian Codegraph @

libstdc++-v3/testsuite/25_algorithms/copy/108846.cc

raw
1 // { dg-do run }
2
3 #include <algorithm>
4 #include <testsuite_hooks.h>
5
6 // PR libstdc++/108846 std::copy, std::copy_n and std::copy_backward
7 // on potentially overlapping subobjects
8
9 struct B {
10 B(int i, short j) : i(i), j(j) {}
11 int i;
12 short j;
13 };
14 struct D : B {
15 D(int i, short j, short x) : B(i, j), x(x) {}
16 short x; // Stored in tail padding of B
17 };
18
19 void
20 test_pr108846()
21 {
22 D ddst(1, 2, 3);
23 D dsrc(4, 5, 6);
24 B *dst = &ddst;
25 B *src = &dsrc;
26 // If this is optimized to memmove it will overwrite tail padding.
27 std::copy(src, src+1, dst);
28 // Check tail padding is unchanged:
29 VERIFY(ddst.x == 3);
30 // Check B subobject was copied:
31 VERIFY(ddst.i == 4 && ddst.j == 5);
32 #if __cpp_lib_ranges >= 201911L
33 ddst.i = ddst.j = 99;
34 std::ranges::copy(src, src+1, dst);
35 VERIFY(ddst.x == 3);
36 VERIFY(ddst.i == 4 && ddst.j == 5);
37 #endif
38 }
39
40 struct B2 {
41 B2(int i, short j) : i(i), j(j) {}
42 B2& operator=(B2& b) { i = b.i; j = b.j; return *this; }
43 int i;
44 short j;
45 };
46 struct D2 : B2 {
47 D2(int i, short j, short x) : B2(i, j), x(x) {}
48 short x; // Stored in tail padding of B2
49 };
50
51 void
52 test_non_const_copy_assign()
53 {
54 D2 ddst(1, 2, 3);
55 D2 dsrc(4, 5, 6);
56 B2 *dst = &ddst;
57 B2 *src = &dsrc;
58 // Ensure the not-taken trivial copy path works for this type.
59 std::copy(src, src+1, dst);
60 // Check tail padding is unchanged:
61 VERIFY(ddst.x == 3);
62 // Check B subobject was copied:
63 VERIFY(ddst.i == 4 && ddst.j == 5);
64 #if __cpp_lib_ranges >= 201911L
65 ddst.i = ddst.j = 99;
66 std::ranges::copy(src, src+1, dst);
67 VERIFY(ddst.x == 3);
68 VERIFY(ddst.i == 4 && ddst.j == 5);
69 #endif
70 }
71
72 struct B3 {
73 B3(int i, short j) : i(i), j(j) {}
74 #if __cplusplus >= 201103L
75 B3& operator=(B3& b) = default;
76 #endif
77 int i;
78 short j;
79 };
80 struct D3 : B3 {
81 D3(int i, short j, short x) : B3(i, j), x(x) {}
82 short x; // Stored in tail padding of B3
83 };
84
85 void
86 test_non_const_copy_assign_trivial()
87 {
88 D3 ddst(1, 2, 3);
89 D3 dsrc(4, 5, 6);
90 B3 *dst = &ddst;
91 B3 *src = &dsrc;
92 // If this is optimized to memmove it will overwrite tail padding.
93 std::copy(src, src+1, dst);
94 // Check tail padding is unchanged:
95 VERIFY(ddst.x == 3);
96 // Check B subobject was copied:
97 VERIFY(ddst.i == 4 && ddst.j == 5);
98 #if __cpp_lib_ranges >= 201911L
99 ddst.i = ddst.j = 99;
100 std::ranges::copy(src, src+1, dst);
101 VERIFY(ddst.x == 3);
102 VERIFY(ddst.i == 4 && ddst.j == 5);
103 #endif
104 }
105
106 int main()
107 {
108 test_pr108846();
109 test_non_const_copy_assign();
110 test_non_const_copy_assign_trivial();
111 }