我尝试初始化我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++
您可能希望使用'static_cast(malloc ...)'而不是您使用的C风格转换。我认为'static_cast'可以工作,但你可能需要'reinterpret_cast'。这些演员比C型演员更具体(并且因此更安全)。他们也更容易在代码中挑出。 –
Omnifarious
@Omnifarious,谢谢你的建议! –
“*我需要使用'malloc',而不是'new' *” - 为什么? 'malloc'是C,而不是C++。 'new'是在C++中分配内存的官方方式。对于这个问题,你所做的只是分配一个自动释放的动态数组。为了这个目的,C++有一个'std :: vector'类。 –