Search code examples
c++pointersreference

Why would it be necessary to use (&*ptr) this format?


I am reading sample code regarding to how to write destroy():

template<class T>
inline void destroy(T* pointer)
{
    pointer->~T();
}

template <class FowardIterator>
inline void 
_desstroy_aux(ForwardIterator first,ForwardIterator last,_false_type)
{
    for(;first<last;++first)
    destroy(&*first); 
}

I am not so sure about why using

&*first

I suppose the destroy algorithm is often used with the assumption that the iterators point to allocated memory. So why don't we use destroy(first) directly? Maybe because first could point to elements which are not individually allocated?


Solution

  • The use of &*ptr in C++ is used to obtain a pointer to an element pointed to by an iterator. In the context of the provided code, &*first is being used within a function that is responsible for destroying objects (called _destroy_aux).

    The main reason to use &*ptr in this case is to get a pointer to the object that the iterator points to first. This is necessary because the destroy function (or 'destory', depending on the possible typo in the code) may require a pointer to the object to be destroyed.

    The * operator gets the object pointed to by the iterator first, and then the & operator gets the memory address of that object, thus providing a pointer to the object itself. This memory address is what may be needed to be passed as an argument to the destroy function to perform the destruction of the object pointed to by that iterator.