I'm reviewing code of a custom container and some portions of it create elements like this:
::new( (void*)&buffer[index] ) CStoredType( other );
and some do like this:
::new( &buffer[index] ) CStoredType( other );
So both use placement new to invoke a copy constructor to create an element by copying some other element, but in one case a pointer to the new element storage is passed as is and in another it is casted to void*
.
Does this cast to void*
have any effect?
static_cast converts the pointer of the void* data type to the data type of that variable whose address is stored by the void pointer. In the above example, we used static_cast to convert the void pointer into an int pointer, so that we could print the contents of the variable var.
Why do we use a void pointer in C programs? We use the void pointers to overcome the issue of assigning separate values to different data types in a program. The pointer to void can be used in generic functions in C because it is capable of pointing to any data type.
A void pointer is a pointer that can point to any type of object, but does not know what type of object it points to. A void pointer must be explicitly cast into another type of pointer to perform indirection. A null pointer is a pointer that does not point to an address. A void pointer can be a null pointer.
In C++, we must explicitly typecast return value of malloc to (int *). 2) void pointers in C are used to implement generic functions in C. For example compare function which is used in qsort(). Some Interesting Facts: 1) void pointers cannot be dereferenced.
Yes you could overload operator new for a nonvoid pointer. The cast ensures that the void pointer overload is taken.
For example
void* operator new(size_t s, env * e);
A compilable example:
#include <iostream>
#include <new>
void* operator new(std::size_t, int* x)
{
std::cout << "a side effect!" << std::endl;
return x;
}
int main()
{
int buffer[1];
new ((void*)&buffer[0]) char;
new (&buffer[0]) char;
}
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