C++ 高效的容器 - Vector - 实现底层 - 引用计数类
注意: 本人是原创, 如若发现雷同,后果自负
注意, 将使用C++ 17来实现
将使用统一的名称空间custom
设计
- 为了实现隐式共享, 将使用引用计数来实现
- 计数成员变量使用原子操作
文件名: Ref_count.hpp
名称空间: custom
类名: Ref_count
包含的头文件: cstddef
和 atomic
成员类型 | 类型 | 作用 |
---|---|---|
count_type |
std::size_t |
计数的类型 |
类型 | 成员变量 | 作用 |
---|---|---|
std::atomic<count_type> |
_atomic |
计数 |
函数 |
作用 |
---|---|
inline bool ref() noexcept |
表示有引用的对象, 返回true就是引用成功 |
inline bool deref() noexcept |
表示有对象取消引用, 返回true就是还有对象引用 |
inline count_type count() const noexcept |
返回引用的对象个数 |
实现
// Ref_count.hpp
#ifndef REF_COUNT_HPP
#define REF_COUNT_HPP
#include <cstddef>
#include <atomic>
namespace custom
{
class Ref_count
{
public:
using count_type = std::size_t;
std::atomic<count_type> _atomic;
public:
inline bool ref() noexcept
{
count_type count = _atomic.load();
if (count == 0 || count == invalid_size || count+1 == invalid_size)
{
return false;
}
++_atomic;
return true;
}
inline bool deref() noexcept
{
count_type count = _atomic.load();
if (count == 0)
{
return false;
}
if (count == invalid_size)
{
return true;
}
return (--_atomic) != 0;
}
inline count_type count() const noexcept
{
return _atomic.load();
}
};
} // custom
#endif // REF_COUNT_HPP
上一篇: C++ 高效的容器 - Vector - 设计
下一篇: C++ Vector 实现内存管理基类