allocatorクラス

ヘッダにある、allocatorクラス。
これの動きは

本(Accelerated C++)だけではわかりにくいのでちょっと確認。

#include <iostream>
#include <memory>

class SampleClass {
public:
    SampleClass():val(0) {
        std::cout << "defconst" << std::endl;
    }
    SampleClass(int arg):val(arg) {
        std::cout << "const with " << arg << std::endl;
    }
    SampleClass(const SampleClass& arg) {
        std::cout << "copy const with " << arg.val << std::endl;
        val = arg.val;
    }
    ~SampleClass() {
        std::cout << "dest of " << val << std::endl;
    }
    SampleClass& operator=(const SampleClass& arg) {
        if (&arg != this) {
            std::cout << "= " << arg.val << std::endl;
            val = arg.val;
        } else {
            std::cout << "= self" << std::endl;
        }
        return *this;
    }
private:
    int val;
};

template <class T>
class otherClass {
private:
    std::allocator<T> alloc;
};


int main()
{
    SampleClass a(1);
    SampleClass b(2);
    SampleClass c(3);
    
    std::allocator<SampleClass> alloc;
    
    std::cout << "..start" << std::endl;
    SampleClass*    p = alloc.allocate(3);
    alloc.construct(p    , a);
    alloc.construct(p + 1, b);
    alloc.construct(p + 2, c);
    SampleClass*    q = alloc.allocate(3);
    std::uninitialized_copy(p, p + 3, q);
    alloc.destroy(p + 2);
    alloc.destroy(p + 1);
    alloc.destroy(p);
    std::uninitialized_fill(p + 2, p + 3, b);
    std::cout << "..end" << std::endl;
}

実行結果

const with 1
const with 2
const with 3
..start
copy const with 1
copy const with 2
copy const with 3
copy const with 1
copy const with 2
copy const with 3
dest of 3
dest of 2
dest of 1
copy const with 2
..end
dest of 3
dest of 2
dest of 1