Debian Codegraph @

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

raw
1 // { dg-do run }
2 // { dg-require-normal-mode "debug mode checks use operator-(Iter, Iter)" }
3
4 #include <algorithm>
5 #include <iterator>
6 #include <testsuite_hooks.h>
7
8 const int g = 0;
9
10 struct Iter {
11 typedef long difference_type;
12 typedef int value_type;
13 typedef const int& reference;
14 typedef const int* pointer;
15 #if __cpp_lib_concepts
16 using iterator_category = std::contiguous_iterator_tag;
17 #else
18 typedef std::random_access_iterator_tag iterator_category;
19 #endif
20
21 Iter(const int* p = 0, const int* limit = 0) : ptr(p), limit(limit) { }
22
23 const int& operator*() const {
24 #ifdef __cpp_exceptions
25 if (ptr == limit)
26 throw 1;
27 #endif
28 return *ptr;
29 }
30 const int* operator->() const { return ptr; }
31 const int& operator[](long n) const { return ptr[n]; }
32
33 Iter& operator++() { ++ptr; return *this; }
34 Iter operator++(int) { Iter tmp = *this; ++ptr; return tmp; }
35 Iter& operator--() { --ptr; return *this; }
36 Iter operator--(int) { Iter tmp = *this; --ptr; return tmp; }
37
38 Iter& operator+=(int n) { ptr += n; return *this; }
39 Iter& operator-=(int n) { ptr -= n; return *this; }
40
41 friend Iter operator+(int n, Iter it) { return it += n; }
42 friend Iter operator+(Iter it, int n) { return it += n; }
43 friend Iter operator-(Iter it, int n) { return it -= n; }
44
45 bool operator==(const Iter& it) const { return ptr == it.ptr; }
46 bool operator!=(const Iter& it) const { return ptr != it.ptr; }
47 bool operator<(const Iter& it) const { return ptr < it.ptr; }
48 bool operator>(const Iter& it) const { return ptr > it.ptr; }
49 bool operator<=(const Iter& it) const { return ptr <= it.ptr; }
50 bool operator>=(const Iter& it) const { return ptr >= it.ptr; }
51
52 // std::copy should not need to take the difference between two iterators:
53 friend int operator-(Iter, Iter) { VERIFY( ! "operator- called" ); }
54
55 private:
56 const int* ptr;
57 const int* limit;
58 };
59
60 void
61 test_pr115444_no_difference()
62 {
63 int from = 1;
64 int to = 0;
65 Iter iter(&from);
66 // This should not use operator-(Iter, Iter)
67 std::copy(iter, iter+1, &to);
68 }
69
70 void
71 test_pr115444_exceptional()
72 {
73 #if __cpp_exceptions
74 int from[3] = { 1, 2, 3 };
75 int to[3] = { -1, -1, -1 };
76 Iter iter(from, from+2);
77 try {
78 std::copy(iter, iter + 3, to);
79 } catch (int) {
80 }
81 // std::copy should exit via exception on third dereference.
82 // This precludes using memcpy or memmove to optimize the copying.
83 VERIFY( to[0] == 1 );
84 VERIFY( to[1] == 2 );
85 VERIFY( to[2] == -1 );
86 #endif
87 }
88
89 int main()
90 {
91 test_pr115444_no_difference();
92 test_pr115444_exceptional();
93 }