stl_construct.h
has the following function:
template<typename _T1, typename _T2> inline void _Construct(_T1* __p, const _T2& __value) { ::new(static_cast<void*>(__p)) _T1(__value); }
I want to know why casting __p
to void*
is needed, is there any advantage?
A pointer to void may be converted to or from a pointer to any incomplete or object type. A pointer to any incomplete or object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer. Again, it's obvious that conversions to both directions are allowed.
A void pointer can hold any address of any item, but cannot be used as a value, until it is cast and dereferenced to a known pointer type. As such it is of limited use because as soon as you are past the page where it can be seen for its entire lifetime, you don't know what it is, what it is for, how to deal with it.
Casting to void is used to suppress compiler warnings. The Standard says in §5.2. 9/4 says, Any expression can be explicitly converted to type “cv void.” The expression value is discarded.
It guarantees that the pre-defined placement new operator is called, rather than any overload added to the global namespace by user code with the signature void* operator new(std::size_t, _T1*)
.
It ensure a potentially _T1* cast operator does not get unitentionally executed
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With