1
0
mirror of https://github.com/SerenityOS/serenity synced 2024-07-09 08:57:20 +00:00
serenity/Tests/AK/TestOwnPtr.cpp
Andreas Kling b7e847e58b AK: Fix crash during teardown of self-owning objects
We now null out smart pointers *before* calling unref on the pointee.
This ensures that the same smart pointer can't be used to acquire a new
reference to the pointee after its destruction has begun.

I ran into this when destroying a non-empty IntrusiveList of RefPtrs,
but the problem was more general so this fixes it for all of RefPtr,
NonnullRefPtr, OwnPtr and NonnullOwnPtr.
2023-04-21 18:15:00 +02:00

36 lines
837 B
C++

/*
* Copyright (c) 2022, the SerenityOS developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibTest/TestCase.h>
#include <AK/OwnPtr.h>
static u64 deleter_call_count = 0;
TEST_CASE(should_call_custom_deleter)
{
auto deleter = [](auto* p) { if (p) ++deleter_call_count; };
auto ptr = OwnPtr<u64, decltype(deleter)> {};
ptr.clear();
EXPECT_EQ(0u, deleter_call_count);
ptr = adopt_own_if_nonnull(&deleter_call_count);
EXPECT_EQ(0u, deleter_call_count);
ptr.clear();
EXPECT_EQ(1u, deleter_call_count);
}
TEST_CASE(destroy_self_owning_object)
{
struct SelfOwning {
OwnPtr<SelfOwning> self;
};
OwnPtr<SelfOwning> object = make<SelfOwning>();
auto* object_ptr = object.ptr();
object->self = move(object);
object = nullptr;
object_ptr->self = nullptr;
}