I was reading about std::uninitialized_copy
and came across something called voidify
:
Effects: Equivalent to:
for (; first != last; ++result, (void) ++first) //#1----vvvvvvv----------->what does this call to voidify mean here ::new (voidify(*result)) typename iterator_traits<NoThrowForwardIterator>::value_type(*first);
Upon further looking for voidify
, I came to know that it is a function template:
Some algorithms specified in this clause make use of the exposition-only function voidify:
template<class T> constexpr void* voidify(T& obj) noexcept { //#2------vvvvvvvvvv-------------------------------->why does this const_cast to void* is needed return const_cast<void*>(static_cast<const volatile void*>(addressof(obj))); //#3------------------------^^^^^^^^^^^------------->why this static_cast to const volatile void* is needed }
So as we can see that voidify
returns a void*
to obj
or something else I don't quite understand as there are some casts involved and i don't know why they are needed. I've placed comments indicating my doubts. Can someone tell me in steps why is voidify
needed in new (voidify(*result))
and why are the const_cast
and static_cast
needed.
In summary(just to clearly state my doubts) my questions are:
Why do we need to call
voidify
innew (voidify(*result))
. I know that this is using palcement-new but I don't know the reason for callingvoidify
and passing*result
as an argument and then using the return value for placement-new.Why the
const_cast
is used here. Why not some other cast likereinterpret_cast
orstatic_cast
. That is what is the need of choosingconst_cast
here.Why is the
static_cast
used here instead of some other cast.Why can't we just write
return addressof(obj);
orreturn (void*)(addressof(obj);
.
Note that I am trying to understand how the equivalent to
version works. The reason I asked my question in different parts is because I think that dividing it in individual steps and then understanding those individual steps lets us understand a topic better. At the end of the day I want to know how does the equivalent version
work.