C ++効率的なコンテナー-ベクトル実装の低レベル参照カウントクラス
注:私はオリジナルです。類似点が見つかった場合は、結果に対して責任を負います
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