C++と色々

主にC++やプログラムに関する記事を投稿します。

boost::in_place

boost::in_placeを使うと確保したメモリにオブジェクトを後から構築できるようになります。
copy不可なオブジェクトも再構築で再代入のような振る舞いをさせられます。

trivial destructorをもつクラスはデストラクトせずに再構築できます。

#include <iostream>
#include <string>
#include <sstream>
#include <boost/utility/in_place_factory.hpp>

template<class T>
class hoge
{
public:

    //T型分のメモリを確保する
    hoge() : buffer_(reinterpret_cast<T*>(new char[sizeof(T)]))
    {
    }

    //メモリの開放
    ~hoge()
    {
        delete buffer_;
    }

    //確保したメモリにオブジェクトを確保する
    template<class InPlace>
    void construct(const InPlace& p)
    {
        p.template apply<T>(buffer_);
    }

    //オブジェクトの破棄
    void destroy()
    {
        buffer_->~T();
    }

    std::string to_string() const
    {
        return buffer_->to_string();
    }    

private:
    T* buffer_;
};

class point
{
public:
    point(int x, int y) : x_(x), y_(y)
    {
    }

    std::string to_string() const
    {
        std::ostringstream oss;
        oss << "(" << x_ << ", " << y_ << ")";
        return oss.str();
    }

private:
    int x_;
    int y_;
};

int main()
{
    hoge<point> a;//メモリを確保
    a.construct(boost::in_place(100, 200));//オブジェクトを構築
    std::cout << a.to_string() << std::endl;

    //point型はtrivial destructorなのでデストラクトせず再構築できる

    a.construct(boost::in_place(300, 400));//再構築
    std::cout << a.to_string() << std::endl;

    return 0;
}

実行結果

(100, 200)
(300, 400)
続行するには何かキーを押してください . . .

参考文献
"デストラクタを呼ばずに再構築":http://d.hatena.ne.jp/melpon/20100308/1267998293(2012/11/22アクセス)