如何用deleter调用unique_ptr构造函数?

时间:2017-10-21 00:10:39

标签: c++

我尝试初始化std::unique_ptr,但无法编译:

error: no matching function for call to ‘std::unique_ptr<int, void (*)(int*)>::unique_ptr(int*, void (&)(void*) throw ())’

m_head((int*)malloc(m_capacity * sizeof(int)), std::free) {
                                                        ^

这是我的代码:

class deque {
    const int INC_ARRAY = 2;

    int m_front, m_back;
    int m_capacity;
    std::unique_ptr<int, void (*)(int *)> m_head;

public:
    const int EMPTY_DEQUE = -1;

    /**
     * @brief Constructor
     */
    deque()
        : m_front{INC_ARRAY - 1}, m_back{INC_ARRAY},
        m_capacity{2 * INC_ARRAY},
        m_head{(int*)malloc(m_capacity * sizeof(int)), std::free} {
    }
};

我需要使用malloc,而不是new。如何正确初始化?

P.S。我正在学习C ++

1 个答案:

答案 0 :(得分:6)

std::free的签名是void free(void*)。它没有int*。更改您的删除类型。

std::unique_ptr<int, void(*)(void*)> m_head;