无法初始化std :: unique_ptr

时间:2018-03-14 01:09:45

标签: c++ c++14

我写了一个堆栈类:

template <class child_t>
class stack {
    const size_t c_init_cap = 12;
    size_t m_size;
    size_t m_capacity;
    std::unique_ptr<child_t[]> m_head;
public:
    /**
     * @brief Default constructor
     */
    stack() : m_size{0}, m_capacity{c_init_cap},
        m_head{std::make_unique<child_t[]>(new child_t[m_capacity])}
    {}
    /**
     * @brief Copy constructor (deleted)
     * @param other Reference to an original object
     */
    stack(const stack &other) = delete;
    /**
     * @brief Move constructor (default)
     * @param other R-value reference to an original object
     */
    stack(stack &&other) = default;
    /**
     * @brief Destructor
     */
    ~stack() {}
    /**
     * @brief Move assigment (default)
     * @param other R-value reference to an original object
     */
    stack& operator =(stack &&other) = default;
    /**
     * @brief Pushes a new value into the stack
     * @param value New value
     */
    void push(child_t value) {
        if (m_size == m_capacity) { increase(); }
        m_head[m_size++] = std::move(value);
    }
    /**
     * @brief Pops a top value from the stack
     */
    void pop() { --m_size; }
    /**
     * @brief Returns a reference to a top value of the stack
     * @return Top value
     */
    child_t &top() { return m_head[m_size - 1]; }
    /**
     * @brief Returns a reference to a top value of the stack
     * @return Top value
     */
    const child_t &top() const { return m_head[m_size - 1]; }
    /**
     * @brief Returns a stack size
     * @return Stack size
     */
    size_t size() const { return m_size; }
    /**
     * @brief Checks if the stack is empty
     * @return Check result
     */
    bool empty() const { return m_size == 0; }
private:
    /**
     * @brief Increases the pre-allocated capacity of the buffer doubly
     */
    void increase() {
        m_capacity <<= 1;
        auto tmp = new child_t[m_capacity];
        std::copy(m_head, m_head + m_size - 1, tmp);
        m_head.reset(tmp);
    }
};

但我在构建时遇到错误:

/home/Task_3_3/task_3_3/stack.h:20: error: no matching function for call to ‘make_unique<int []>(int*)’
         m_head{std::make_unique<child_t[]>(new child_t[m_capacity])}
                ~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~

这是什么意思?我该如何解决?
P.S。我只学习C ++,所以我仍然是一个noobie ...

2 个答案:

答案 0 :(得分:5)

正确使用std::make_unique数组类型是为了提供数组的大小作为参数。

初始化m_head的正确方法是m_head{std::make_unique<child_t[]>(m_capacity)}

答案 1 :(得分:1)

使用raise ArgumentError.new("Here: #{symbol}") 的最重要原因可能是避免使用make_unique运算符。您可以阅读此问题以获取更多信息:Exception safety and make_unique

所以在你的情况下:

new