Reference count (Rc aka shared_ptr) implementation

This commit is contained in:
Imbus 2025-01-12 11:31:50 +01:00
parent b17d7543cf
commit 168f49d0b2
2 changed files with 84 additions and 0 deletions

5
refcount/Makefile Normal file
View file

@ -0,0 +1,5 @@
# Only define if needed:
# TARGET = main.elf
# SRCS = main.cc
include ../config.mk

79
refcount/main.cc Normal file
View file

@ -0,0 +1,79 @@
#include <iostream>
/* RefCounter. Analogous to std::shared_ptr. */
template <typename T>
class Rc {
T *data;
std::size_t *refs;
public:
explicit Rc(const T &); // Copy ctor
explicit Rc(T &&); // Move ctor
Rc(const Rc &); // Copy ctor
Rc(Rc &&); // Move ctor
void operator=(const Rc &); // Copy assign
void operator=(Rc &&); // Move assign
~Rc();
const T &borrow() noexcept;
T &borrow_mut() noexcept;
};
template <typename T>
Rc<T>::Rc(const T &data)
: Rc(std::move(data)) {}
template <typename T>
Rc<T>::Rc(T &&data)
: data(new T(std::move(data)))
, refs(new std::size_t(1)) {}
template <typename T>
Rc<T>::Rc(const Rc &other)
: data(other.data)
, refs(other.refs) {
refs++;
}
template <typename T>
Rc<T>::Rc(Rc &&other)
: data(other.data)
, refs(other.refs) {
other.refs = nullptr;
other.data = nullptr;
}
template <typename T>
void Rc<T>::operator=(const Rc &other) {}
template <typename T>
void Rc<T>::operator=(Rc &&other) {}
template <typename T>
Rc<T>::~Rc() {
if (--refs == 0)
delete data;
}
template <typename T>
const T &Rc<T>::borrow() noexcept {
return *data;
}
template <typename T>
T &Rc<T>::borrow_mut() noexcept {
return *data;
}
int main() {
std::cout << "Template" << std::endl;
Rc<int> a = Rc(10);
auto b = Rc(10);
b.borrow_mut()++;
std::cout << a.borrow() << std::endl;
std::cout << b.borrow() << std::endl;
a = b;
}