80 lines
1.5 KiB
C++
80 lines
1.5 KiB
C++
|
#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;
|
||
|
}
|