无法初始化标准::unique_ptr

Can't initialize std::unique_ptr

本文关键字:unique ptr 标准 初始化      更新时间:2023-10-16

我写了一个堆栈类:

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])}
                ~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~

什么意思?我该如何解决?
附言我只学C++,所以我还是个菜鸟......

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

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

使用

make_unique 的最重要原因可能是避免使用运算符new。您可以阅读此查询以获取更多信息:异常安全和make_unique。

所以在你的情况下:

std::make_unique<child_t[]>(m_capacity);