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 // UNSUPPORTED: c++03, c++11, c++14, c++17
10 // UNSUPPORTED: libcpp-no-concepts
11 // UNSUPPORTED: gcc-10
12 
13 // If we have a copy-propagating cache, when we copy ZeroOnDestroy, we will get a
14 // dangling reference to the copied-from object. This test ensures that we do not
15 // propagate the cache on copy.
16 
17 #include <ranges>
18 
19 #include "test_macros.h"
20 #include "types.h"
21 
22 struct ZeroOnDestroy : std::ranges::view_base {
23   unsigned count = 0;
24   int buff[8] = {1, 2, 3, 4, 5, 6, 7, 8};
25 
26   constexpr ForwardIter begin() { return ForwardIter(buff); }
27   constexpr ForwardIter begin() const { return ForwardIter(); }
28   constexpr ForwardIter end() { return ForwardIter(buff + 8); }
29   constexpr ForwardIter end() const { return ForwardIter(); }
30 
31   ~ZeroOnDestroy() {
32     memset(buff, 0, sizeof(buff));
33   }
34 
35   static auto dropFirstFour() {
36     ZeroOnDestroy zod;
37     std::ranges::drop_view dv(zod, 4);
38     // Make sure we call begin here so the next call to begin will
39     // use the cached iterator.
40     assert(*dv.begin() == 5);
41     // Intentionally invoke the copy ctor here.
42     return std::ranges::drop_view(dv);
43   }
44 };
45 
46 int main(int, char**) {
47   auto noDanlingCache = ZeroOnDestroy::dropFirstFour();
48   // If we use the cached version, it will reference the copied-from view.
49   // Worst case this is a segfault, best case it's an assertion fired.
50   assert(*noDanlingCache.begin() == 5);
51 
52   return 0;
53 }
54