Serenity Operating System
at master 79 lines 1.5 kB view raw
1/* 2 * Copyright (c) 2020, the SerenityOS developers. 3 * 4 * SPDX-License-Identifier: BSD-2-Clause 5 */ 6 7#include <LibTest/TestCase.h> 8 9#include <AK/NeverDestroyed.h> 10#include <AK/StdLibExtras.h> 11 12struct Counter { 13 Counter() = default; 14 15 ~Counter() { ++num_destroys; } 16 17 Counter(Counter const&) 18 { 19 ++num_copies; 20 } 21 22 Counter(Counter&&) { ++num_moves; } 23 24 int num_copies {}; 25 int num_moves {}; 26 int num_destroys {}; 27}; 28 29TEST_CASE(should_construct_by_copy) 30{ 31 Counter c {}; 32 AK::NeverDestroyed<Counter> n { c }; 33 34 EXPECT_EQ(1, n->num_copies); 35 EXPECT_EQ(0, n->num_moves); 36} 37 38TEST_CASE(should_construct_by_move) 39{ 40 Counter c {}; 41 AK::NeverDestroyed<Counter> n { move(c) }; 42 43 EXPECT_EQ(0, n->num_copies); 44 EXPECT_EQ(1, n->num_moves); 45} 46 47NO_SANITIZE_ADDRESS static void should_not_destroy() 48{ 49 Counter* c = nullptr; 50 { 51 AK::NeverDestroyed<Counter> n {}; 52 // note: explicit stack-use-after-scope 53 c = &n.get(); 54 } 55 EXPECT_EQ(0, c->num_destroys); 56} 57 58TEST_CASE(should_not_destroy) 59{ 60 should_not_destroy(); 61} 62 63TEST_CASE(should_provide_dereference_operator) 64{ 65 AK::NeverDestroyed<Counter> n {}; 66 EXPECT_EQ(0, n->num_destroys); 67} 68 69TEST_CASE(should_provide_indirection_operator) 70{ 71 AK::NeverDestroyed<Counter> n {}; 72 EXPECT_EQ(0, (*n).num_destroys); 73} 74 75TEST_CASE(should_provide_basic_getter) 76{ 77 AK::NeverDestroyed<Counter> n {}; 78 EXPECT_EQ(0, n.get().num_destroys); 79}