C++ Efficient Container-Vector-Implement Low-Level-Reference Counting Class
Note: I am original, if you find similarities, you will be responsible for the consequences
Note that C++ 17
will be used to implement the unified namespacecustom
design
- In order to achieve implicit sharing, reference counting will be used to achieve
- Count member variables using atomic operations
File name: Ref_count.hpp
namespace: custom
class name: Ref_count
included header files: cstddef
andatomic
Member type | Types of | effect |
---|---|---|
count_type |
std::size_t |
计数的类型 |
Types of | Member variables | effect |
---|---|---|
std::atomic<count_type> |
_atomic |
计数 |
函数 |
作用 |
---|---|
inline bool ref() noexcept |
表示有引用的对象, 返回true就是引用成功 |
inline bool deref() noexcept |
表示有对象取消引用, 返回true就是还有对象引用 |
inline count_type count() const noexcept |
返回引用的对象个数 |
achieve
// 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
Previous: C++ Efficient Container-Vector-Design
Next: C++ Vector implements memory management base class