| 8 | #include "fl/stl/move.h" |
| 9 | |
| 10 | FL_TEST_FILE(FL_FILEPATH) { |
| 11 | |
| 12 | namespace weak_ptr_test { |
| 13 | |
| 14 | // Test class that does NOT inherit from fl::Referent (non-intrusive) |
| 15 | class TestClass { |
| 16 | public: |
| 17 | TestClass() : mValue(0), mDestructorCalled(nullptr) {} |
| 18 | TestClass(int value) : mValue(value), mDestructorCalled(nullptr) {} |
| 19 | |
| 20 | // Constructor that allows tracking destructor calls |
| 21 | TestClass(int value, bool* destructor_flag) : mValue(value), mDestructorCalled(destructor_flag) {} |
| 22 | |
| 23 | ~TestClass() { |
| 24 | if (mDestructorCalled) { |
| 25 | *mDestructorCalled = true; |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | int getValue() const { return mValue; } |
| 30 | void setValue(int value) { mValue = value; } |
| 31 | |
| 32 | private: |
| 33 | int mValue; |
| 34 | bool* mDestructorCalled; |
| 35 | }; |
| 36 | |
| 37 | FL_TEST_CASE("fl::weak_ptr default construction") { |
| 38 | fl::weak_ptr<TestClass> weak; |
| 39 | FL_CHECK_EQ(weak.use_count(), 0); |
| 40 | FL_CHECK(weak.expired()); |
| 41 | |
| 42 | auto shared = weak.lock(); |
| 43 | FL_CHECK(!shared); |
| 44 | FL_CHECK_EQ(shared.get(), nullptr); |
| 45 | } |
| 46 | |
| 47 | FL_TEST_CASE("fl::weak_ptr construction from shared_ptr") { |
| 48 | fl::shared_ptr<TestClass> shared = fl::make_shared<TestClass>(42); |
| 49 | FL_CHECK_EQ(shared.use_count(), 1); |
| 50 | |
| 51 | fl::weak_ptr<TestClass> weak(shared); |
| 52 | FL_CHECK_EQ(weak.use_count(), 1); |
| 53 | FL_CHECK_EQ(shared.use_count(), 1); // weak_ptr doesn't increase shared count |
| 54 | FL_CHECK(!weak.expired()); |
| 55 | |
| 56 | auto locked = weak.lock(); |
| 57 | FL_CHECK(locked); |
| 58 | FL_CHECK_EQ(locked.use_count(), 2); // lock() creates a shared_ptr |
| 59 | FL_CHECK_EQ(locked->getValue(), 42); |
| 60 | } |
| 61 | |
| 62 | FL_TEST_CASE("fl::weak_ptr copy construction") { |
| 63 | fl::shared_ptr<TestClass> shared = fl::make_shared<TestClass>(42); |
| 64 | fl::weak_ptr<TestClass> weak1(shared); |
| 65 | fl::weak_ptr<TestClass> weak2(weak1); |
| 66 | |
| 67 | FL_CHECK_EQ(weak1.use_count(), 1); |
nothing calls this directly
no test coverage detected