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