xref: /llvm-project/libcxx/test/std/strings/basic.string/string.access/at.pass.cpp (revision 25838c6dacca8203b4478ac2c16e563b51c3708b)
1 //===----------------------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 // <string>
10 
11 // const_reference at(size_type pos) const;
12 //       reference at(size_type pos);
13 
14 // When back-deploying to macosx10.7, the RTTI for exception classes
15 // incorrectly provided by libc++.dylib is mixed with the one in
16 // libc++abi.dylib and exceptions are not caught properly.
17 // XFAIL: with_system_cxx_lib=macosx10.7
18 
19 #include <string>
20 #include <stdexcept>
21 #include <cassert>
22 
23 #include "min_allocator.h"
24 
25 #include "test_macros.h"
26 
27 template <class S>
28 void
29 test(S s, typename S::size_type pos)
30 {
31     const S& cs = s;
32     if (pos < s.size())
33     {
34         assert(s.at(pos) == s[pos]);
35         assert(cs.at(pos) == cs[pos]);
36     }
37 #ifndef TEST_HAS_NO_EXCEPTIONS
38     else
39     {
40         try
41         {
42             TEST_IGNORE_NODISCARD s.at(pos);
43             assert(false);
44         }
45         catch (std::out_of_range&)
46         {
47             assert(pos >= s.size());
48         }
49         try
50         {
51             TEST_IGNORE_NODISCARD cs.at(pos);
52             assert(false);
53         }
54         catch (std::out_of_range&)
55         {
56             assert(pos >= s.size());
57         }
58     }
59 #endif
60 }
61 
62 int main(int, char**)
63 {
64     {
65     typedef std::string S;
66     test(S(), 0);
67     test(S("123"), 0);
68     test(S("123"), 1);
69     test(S("123"), 2);
70     test(S("123"), 3);
71     }
72 #if TEST_STD_VER >= 11
73     {
74     typedef std::basic_string<char, std::char_traits<char>, min_allocator<char>> S;
75     test(S(), 0);
76     test(S("123"), 0);
77     test(S("123"), 1);
78     test(S("123"), 2);
79     test(S("123"), 3);
80     }
81 #endif
82 
83   return 0;
84 }
85