vendredi 21 octobre 2016

Why cannot I delete unique_ptr

When I have an unique pointer to a single object, I can delete it with reset():

std::unique_ptr<char> variable(new char);
variable.reset();

However, this does not work for an std::unique_ptr containing an array. Why? What is the proper way to delete such pointer?

I am using Embarcadero C++ Builder 10.1. and the relevant standard is C++11.

My observations

When I have an unique pointer containing an array, this fails to compile:

std::unique_ptr<char[]> variable(new char[10]);
variable.reset();

Error message is no matching function to call for 'reset'.

This also fails:

std::unique_ptr<char[]> variable(new char[10]);
variable.reset(nullptr);

Error messages are cannot initialize a variable of type 'pointer' (aka 'char *') with an lvalue of type '<bound member function type>' and assigning to '<bound member function type>' from incompatible type '_Null_ptr_type' (aka 'nullptr_t').

This compiles:

std::unique_ptr<char[]> variable(new char[10]);
variable = nullptr;

Relevant code from <memory>

_Myt& operator=(_Null_ptr_type) _NOEXCEPT
    {   // assign a null pointer
    reset(pointer());
    return (*this);
    }

_NOINLINE void reset(_Null_ptr_type _Ptr) _NOEXCEPT
    {   // establish new null pointer
    pointer _Old = this->_Myptr;
    this->_Myptr = _Ptr;
    if (_Old != pointer())
        this->get_deleter()(_Old);
    }

template<class _Uty,
    class = _Enable_ctor_reset<_Uty> >
void reset(_Uty _Ptr) _NOEXCEPT
    {   // establish new pointer
    pointer _Old = get();
    this->_Myptr() = _Ptr;
    if (_Old != pointer())
        this->get_deleter()(_Old);
    }

Aucun commentaire:

Enregistrer un commentaire