Add specialized operator=() to handle nullptr assignment

This commit is contained in:
Josh Holtrop 2026-02-27 14:50:48 -05:00
parent e3cdfb1bfa
commit b695ce7758
2 changed files with 31 additions and 0 deletions

View File

@ -23,6 +23,7 @@
#pragma once
#include <atomic>
#include <cstddef>
#include <functional>
#include <type_traits>
@ -59,6 +60,16 @@ public:
}
}
rcp & operator=(nullptr_t) noexcept
{
if (ptr)
{
ptr->rcp_dec();
ptr = nullptr;
}
return *this;
}
rcp & operator=(const rcp & other)
{
if (ptr != other.ptr)

View File

@ -448,6 +448,25 @@ void test_external_class()
assert(external_destruct == before + 2);
}
void test_assign_nullptr()
{
int constructed_before = mybase_construct;
int destructed_before = mybase_destruct;
{
rcp<MyBase> base = MyBase::create(6, 6);
assert(mybase_construct == constructed_before + 1);
assert(mybase_destruct == destructed_before);
base = nullptr;
assert(mybase_construct == constructed_before + 1);
assert(mybase_destruct == destructed_before + 1);
base = nullptr;
assert(mybase_construct == constructed_before + 1);
assert(mybase_destruct == destructed_before + 1);
}
assert(mybase_construct == constructed_before + 1);
assert(mybase_destruct == destructed_before + 1);
}
int main(int argc, char * argv[])
{
test_class_hierarchy();
@ -477,5 +496,6 @@ int main(int argc, char * argv[])
test_hash();
test_class_template();
test_external_class();
test_assign_nullptr();
return 0;
}