Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does casting a pointer to "void*" have any effect when placement new is called?

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?

like image 768
sharptooth Avatar asked Dec 09 '11 09:12

sharptooth


People also ask

What does casting to void pointer do?

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.

What is one reason you would use a void pointer?

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.

Can a void pointer point to anything?

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.

Can void pointer be freed?

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.


2 Answers

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);
like image 173
Johannes Schaub - litb Avatar answered Nov 06 '22 12:11

Johannes Schaub - litb


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;
}
like image 23
GManNickG Avatar answered Nov 06 '22 13:11

GManNickG