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