029: emplace_back()

emplace_back() を定義します。C++11 で追加された関数です。

emplace_back() と push_back() の関係は、emplace() と insert() の関係とほぼ同じです。

template <typename T>
class myvector
{
...

    /**
     * @brief      Appends a new element to the end of the container. The arguments
     *             args... are forwarded to the constructor as std::forward<Args>(args)....
     *             If the new size() is greater than capacity() then all iterators
     *             and references (including the past-the-end iterator) are invalidated.
     *             Otherwise only the past-the-end iterator is invalidated.
     * @param[in]  args: Arguments to forward to the constructor of the element.
     * @tparam     Args: Parameter pack for constructor's arguments.
     * @return     A reference to the inserted element.
     */
    template <class... Args>
    reference emplace_back(Args&&... args)
    {
        if (need_twice_capacity()) {
            reallocation(twice_length(), realloc_switcher());
        }
        new(&heap_[size_]) value_type(std::forward<Args&&>(args)...);
        size_++;

        return heap_[size_ - 1];
    }

    ...

};
push_back() とほぼ同じ処理です。違いは、placement-new する時に、引数をコンストラクタのパラメータとして渡す点です。


全ソースコード: https://github.com/suomesta/myvector/tree/master/029

0 件のコメント:

コメントを投稿