使用其他参数引用const默认参数?

时间:2015-03-04 04:42:28

标签: c++ parameters reference copy-constructor

我正在创建一个自定义的forward_list,但我遇到问题this copy constructor. 问题是,在我的forward_list中我有一个私有变量A& heap;,我想用alloc实例化它,除非没有提供alloc(我不明白这是怎么回事,因为alloc是一个引用参数,因此必须提供?)。 因此,如果不以某种方式提供,我可以实例化alloc的唯一地方是在init列表中(因为它是一个引用),但我不能,因为allocator_traits需要other.get_allocator(),这是另一个参数。


template<typename T, typename A = std::allocator<T>>
class forward_list
{
    ...
private:
    struct node
    {
        T data;
        std::unique_ptr<T> next;
    };
    std::unique_ptr<node> root_;
    std::unique_ptr<node> leaf_;
    size_t count_;
    const A& heap;
}

/* Copy constructor. Constructs the container with the copy of the contents of other.
 * If alloc is not provided, allocator is obtained by calling
 * std::allocator_traits<allocator_type>::select_on_container_copy_construction(other.get_allocator());
 */
forward_list(const forward_list& other, const A& alloc = A())
 : heap(std::allocator_traits<allocator_type>::select_on_container_copy_construction(other.get_allocator()))
{
}

1 个答案:

答案 0 :(得分:0)

inline forward_list(const forward_list& other)
 : root_(other.root_), leaf_(other.leaf_), count_(other.count_), heap(std::allocator_traits<allocator_type>::select_on_container_copy_construction(other.get_allocator())) {};

inline forward_list(const forward_list& other, const A& alloc)
 : root_(other.root_), leaf_(other.leaf_), count_(other.count_), heap(alloc) {};