2017-10-21 49 views
0

我尝试初始化我std::unique_ptr但它无法编译:如何使用deleter调用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

您可能希望使用'static_cast (malloc ...)'而不是您使用的C风格转换。我认为'static_cast'可以工作,但你可能需要'reinterpret_cast'。这些演员比C型演员更具体(并且因此更安全)。他们也更容易在代码中挑出。 – Omnifarious

+0

@Omnifarious,谢谢你的建议! –

+0

“*我需要使用'malloc',而不是'new' *” - 为什么? 'malloc'是C,而不是C++。 'new'是在C++中分配内存的官方方式。对于这个问题,你所做的只是分配一个自动释放的动态数组。为了这个目的,C++有一个'std :: vector'类。 –

回答

6

std::free的签名是void free(void*)。它不需要int*。更改您的删除者类型。

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

传递正确签名的更安全的方法是使用['decltype()'](http://en.cppreference.com/w/cpp/language/decltype),例如:'std :: unique_ptr m_head;' –

+2

@RemyLebeau:'decltype(&std :: free)',否则,是的。 –