简体   繁体   中英

How to call unique_ptr constructor with deleter?

I try to initialize my std::unique_ptr but it fails to compile:

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) {
                                                        ^

This my code:

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} {
    }
};

I need to use malloc , not new . How to initialize it correctly?

PS I'm learning C++ only

The signature of std::free is void free(void*) . It doesn't take int* . Change your deleter type.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM