Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The advantage cast pointer to void* when use new

Tags:

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?

like image 504
icecity96 Avatar asked Jul 05 '16 01:07

icecity96


People also ask

What does casting a pointer to void do?

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.

What are the advantages and disadvantages of a void pointer?

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.

What is void cast in C?

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.


2 Answers

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*).

like image 164
Brian Bi Avatar answered Oct 01 '22 12:10

Brian Bi


It ensure a potentially _T1* cast operator does not get unitentionally executed

like image 35
Soren Avatar answered Oct 01 '22 10:10

Soren