Question

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?

Was it helpful?

Solution

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);

OTHER TIPS

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top