I have a question related to placement new.
When dealing with objects, in order to destroy an object created with placement new it has to be called the destructor of the object explicity; that is:

#include <new>
using namespace std;
//The following command really allocates the splace
char * rawStorage = new char[ 2000 ];
//Placement new: It creates MyObject using the previous allocated space
MyObject* pmyObject = new (rawStorage) MyObject();
//To destroy MyObject
pmyObject->~MyObject();

//To destroy the raw storage
delete[] rawStorage

However, in some cases a part from building and object I have to use the raw storage in order to store an unsigned char array; that is:

#include <new>
using namespace std;

char * rawStorage = new char[ 2000 ];
//Placement new
unsigned char* arrayUnsignedChar = new (rawStorage) unsigned char[ 1000 ];
//The question is: how can be destroyed the "arrayUnsignedChar"
arrayUnsignedChar->?????????????

//To destroy the raw storage
delete[] rawStorage

So, how can I "destroy", not the raw storage, but the "arrayUnsignedChar"?
Perhaps in the case of an array of UnsignedChar there is no need to call any kind of destructor or function -perhaps it could be done a "reset" of the contents doing something like: memset(arrayUnsignedChar, 0x00, size);-

>So, how can I "destroy", not the raw storage, but the "arrayUnsignedChar"?
Why are you trying to call the destructor for a built-in type anyway?

You are rigth. In case of working with built-in types, not objects, it has no sense to call any destructor; so it is only necessary the following code:

#include <new>
using namespace std;
//Here is where the real storage is done
char * rawStorage = new char[ 2000 ];
//Placement new
unsigned char* arrayUnsignedChar = new (rawStorage) unsigned char[ 1000 ];
//Use the "arrayUnsignedChar"
//......
// Again reuse the same storage for a new array of unsigned chars
// the new array "array2UnsignedChar" will point to the same memory location as the
// previous "arrayUnsignedChar"
unsigned char* array2UnsignedChar = new (rawStorage) unsigned char[ 1000 ]
//......
//Finally destroy the raw storage
delete[] rawStorage

Thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.