union
{
byte* data;
char* ch;
char16_t* ch16;
char32_t* ch32;
}
m_Buffer;
I keep track of which format of data I'm storing in the buffer and use the different name depending on what kind of unit (char, char16_t, etc.) I'm storing in the buffer.
My question is, is it safe to delete[] the array of whatever unit type on any member regardless of how I initialized one of the pointers? For example:
m_Buffer.ch16 = new char16_t[ charCount ]; delete[] m_Buffer.data; // Is this valid... does it free the above allocation? m_Buffer.data = new byte[ charCount * sizeof(char16_t) ]; delete[] m_Buffer.ch16; // Is this valid... does it free the above allocation?
Also, is the pointer I assign to a given union member kept properly regardless of which one I access for indexing into the array? For example:
m_Buffer.data = new byte[ charCount * sizeof(char16_t) ];
// Fill the string buffer with spaces.
for( uint i = 0; i < charCount - 1; i++ )
{
m_Buffer.ch16[ i ] = (char16_t)' '; // Is this valid?
}
// Terminate the string.
m_Buffer.ch16[ charCount - 1 ] = (char16_t)'\0';
and
m_Buffer.ch16 = new char16_t[ charCount ]; m_UnitCount = charCount; // Then somewhere else: byte* someOtherBuffer = new byte[ charCount * sizeof(char16_t) ]; memcpy( someOtherBuffer, m_Buffer.data, m_UnitCount * sizeof(char16_t) ); delete[] m_Buffer.data; m_Buffer.data = someOtherBuffer; m_UnitCount = charCount;
My knowledge of unions and delete is very rusty. Does all of the above code work as expected?












