shared_array

meltさんのとこからもらってきたシリーズ第2弾


はい。shared_arrayです。

meltさんのをboost::shared_arrayのインターフェースに合わせただけです。


shared_arrayはC++0xのTR1ライブラリには含まれないので、しばらく使いそうですね

#include <functional> // less

namespace shand {

template <class Type>
class shared_array {
    Type*   object_;    // 生のポインタ
    int*    counter_;   // 参照カウンタ

public:
    typedef Type element_type;
    typedef Type value_type;
    typedef Type* pointer;

    shared_array()
        : object_(0), counter_(0) {}

    shared_array(const shared_array& src)
        : object_(0), counter_(0) { set(src); }

    explicit shared_array(Type* object)
        : object_(object), counter_(new int(1)) {}

    ~shared_array() { release(); }

    // ポインタ取得
    Type* get() const { return object_; }

    // 参照カウント取得
    long use_count() const
    {
        if (!counter_)
            return 0;
        return *counter_;
    }

    // 参照先が1つか判断
    bool unique() const { return use_count() == 1; }

    shared_array& operator=(const shared_array& rhs) { set(rhs); return *this; }

    Type& operator[](int index) const
    {
        return object_[index];
    }

    bool operator!() const { return object_ == 0; }

    operator bool() const { return object_ != 0; }

private:
    void set(const shared_array& src)
    {
        if (this != &src) {
            release();
            object_  = src.object_;
            counter_ = src.counter_;

            if (counter_ != 0)
                ++*counter_;
        }
    }

    void release()
    {
        // 参照カウンタを減らす
        if (counter_ != 0 && --*counter_ == 0) {
            delete[] object_;
            delete   counter_;
        }
        object_  = 0;
        counter_ = 0;
    }
};

template<class Type>
inline bool operator==(shared_array<Type> const & lhs, shared_array<Type> const & rhs)
{
    return lhs.get() == rhs.get();
}

template<class Type>
inline bool operator!=(shared_array<Type> const & lhs, shared_array<Type> const & rhs)
{
    return lhs.get() != rhs.get();
}

template<class Type>
inline bool operator<(shared_array<Type> const & lhs, shared_array<Type> const & rhs)
{
    return std::less<Type*>()(lhs.get(), rhs.get());
}


} // namespace shand

サンプル

#include <iostream>
#include <shand/shared_array.hpp>

using namespace std;
using namespace shand;

int main()
{
    int size = 3;
    shared_array<int> p(new int[size]);

    p[0] = 3;
    p[1] = 1;
    p[2] = 4;

    for (int index = 0; index < size; index++)
        cout << p[index] << endl;

    return 0;
}


本家
http://boost.cppll.jp/HEAD/libs/smart_ptr/shared_array.htm


ライブラリまとめ