Add swap() and support std::hash

This commit is contained in:
Josh Holtrop 2026-02-24 19:53:59 -05:00
parent 464527a34d
commit d2b6755704
2 changed files with 43 additions and 0 deletions

View File

@ -23,6 +23,7 @@
#pragma once #pragma once
#include <atomic> #include <atomic>
#include <functional>
#include <type_traits> #include <type_traits>
/** /**
@ -118,6 +119,13 @@ public:
other.ptr = nullptr; other.ptr = nullptr;
} }
void swap(rcp & other) noexcept
{
T * tmp = ptr;
ptr = other.ptr;
other.ptr = tmp;
}
void reset() void reset()
{ {
if (ptr) if (ptr)
@ -179,6 +187,18 @@ public:
friend rcp<V> rcp_dynamic_cast(rcp<W> && other); friend rcp<V> rcp_dynamic_cast(rcp<W> && other);
}; };
namespace std
{
template <typename T>
struct hash<rcp<T>>
{
size_t operator()(const rcp<T> & p) const noexcept
{
return hash<const void *>()(static_cast<const void *>(p.get_raw()));
}
};
}
template <typename T, typename U> template <typename T, typename U>
rcp<T> rcp_dynamic_cast(const rcp<U> & other) rcp<T> rcp_dynamic_cast(const rcp<U> & other)
{ {

View File

@ -1,5 +1,6 @@
#include <rcp.h> #include <rcp.h>
#include <cassert> #include <cassert>
#include <unordered_map>
#include <vector> #include <vector>
static int mybase_construct; static int mybase_construct;
@ -313,6 +314,26 @@ protected:
~Counter() { external_destruct++; } ~Counter() { external_destruct++; }
}; };
void test_swap()
{
MyB a = MyB::create(1, 2);
MyB b = MyB::create(3, 4);
a.swap(b);
assert(a->x == 3);
assert(b->x == 1);
}
void test_hash()
{
MyB a = MyB::create(1, 2);
MyB b = a;
std::unordered_map<MyB, int> map;
map[a] = 42;
assert(map[b] == 42);
MyB c = MyB::create(3, 4);
assert(map.find(c) == map.end());
}
void test_external_class() void test_external_class()
{ {
int before = external_destruct; int before = external_destruct;
@ -347,6 +368,8 @@ int main(int argc, char * argv[])
test_dynamic_cast_failure(); test_dynamic_cast_failure();
test_dynamic_cast_move_success(); test_dynamic_cast_move_success();
test_dynamic_cast_move_failure(); test_dynamic_cast_move_failure();
test_swap();
test_hash();
test_external_class(); test_external_class();
return 0; return 0;
} }