James Kuszmaul | 397f6fe | 2020-01-04 16:21:52 -0800 | [diff] [blame^] | 1 | /*----------------------------------------------------------------------------*/ |
| 2 | /* Copyright (c) 2019 FIRST. All Rights Reserved. */ |
| 3 | /* Open Source Software - may be modified and shared by FRC teams. The code */ |
| 4 | /* must be accompanied by the FIRST BSD license file in the root directory of */ |
| 5 | /* the project. */ |
| 6 | /*----------------------------------------------------------------------------*/ |
| 7 | |
| 8 | #include "wpi/ManagedStatic.h" // NOLINT(build/include_order) |
| 9 | |
| 10 | #include "gtest/gtest.h" |
| 11 | |
| 12 | static int refCount = 0; |
| 13 | |
| 14 | struct StaticTestClass { |
| 15 | StaticTestClass() { refCount++; } |
| 16 | ~StaticTestClass() { refCount--; } |
| 17 | |
| 18 | void Func() {} |
| 19 | }; |
| 20 | |
| 21 | namespace wpi { |
| 22 | TEST(ManagedStaticTest, LazyDoesNotInitialize) { |
| 23 | { |
| 24 | refCount = 0; |
| 25 | wpi::ManagedStatic<StaticTestClass> managedStatic; |
| 26 | ASSERT_EQ(refCount, 0); |
| 27 | } |
| 28 | ASSERT_EQ(refCount, 0); |
| 29 | wpi_shutdown(); |
| 30 | } |
| 31 | |
| 32 | TEST(ManagedStaticTest, LazyInitDoesntDestruct) { |
| 33 | { |
| 34 | refCount = 0; |
| 35 | wpi::ManagedStatic<StaticTestClass> managedStatic; |
| 36 | ASSERT_EQ(refCount, 0); |
| 37 | managedStatic->Func(); |
| 38 | ASSERT_EQ(refCount, 1); |
| 39 | } |
| 40 | ASSERT_EQ(refCount, 1); |
| 41 | wpi_shutdown(); |
| 42 | ASSERT_EQ(refCount, 0); |
| 43 | } |
| 44 | |
| 45 | TEST(ManagedStaticTest, EagerInit) { |
| 46 | { |
| 47 | refCount = 0; |
| 48 | StaticTestClass* test = new StaticTestClass{}; |
| 49 | ASSERT_EQ(refCount, 1); |
| 50 | wpi::ManagedStatic<StaticTestClass> managedStatic( |
| 51 | test, [](void* val) { delete static_cast<StaticTestClass*>(val); }); |
| 52 | ASSERT_EQ(refCount, 1); |
| 53 | managedStatic->Func(); |
| 54 | ASSERT_EQ(refCount, 1); |
| 55 | } |
| 56 | ASSERT_EQ(refCount, 1); |
| 57 | wpi_shutdown(); |
| 58 | ASSERT_EQ(refCount, 0); |
| 59 | } |
| 60 | } // namespace wpi |