无法初始化标准::unique_ptr
Can't initialize std::unique_ptr
我写了一个堆栈类:
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);
相关文章:
- 为什么 std::unique 不调用 std::sort?
- CLANG 编译器 说:变量"PTR"可能未初始化
- 在以唯一ptr为值的C++映射中,动态内存何时会被销毁
- 将 ptr 传递给 ptr 到 A 作为参数传递给 A 的函数是不好的做法吗?
- 为共享 ptr 向量实现复制 c'tor?
- 字符和整数中 **(ptr+1) 的值差异
- C++:在不中断共享的情况下通过引用传递共享 PTR?
- 生成"unique"矩阵
- 如何将派生类从基 ptr 分配给 nlohmann::json
- 引用 std::shared:ptr 以避免引用计数
- 我对 std::unique(算法)C++有问题
- 为什么我不能在不进行任何转换的情况下将浮点数放入任何类型的 ptr 中?
- 在调用函数时,ptr** 和 ptr*& 之间是否有区别,或者首选C++?
- 另一种类型的智能ptr,比如具有弱refs的unique_ptr
- 尝试打印出 *ptr++ 的值,以了解它是如何工作的
- 如何控制共享 ptr 引用计数?
- std::shared_ptr::unique(),复制和线程安全
- 如何在C++03中用自定义谓词调用std::unique
- C++中的指针否定 (!ptr == NULL)
- C++14 unique_ptr并使用已删除的函数'std::unique-ptr' unique_ptr错误