Original Post
Hello, today I was writing some container class that pre-allocates uninitialized memory and uses placement new when needed. After a long search, I realized I can't possibly do that due to the strict aliasing rule.
To my understanding, void* can be casted to something else only if the original variable holding the pointer to void has not been casted to something else yet. So:
Is this correct?
If so, writing a stack-based allocator is impossible, or is there any technique I don't know of to achieve that? I'd like to get the equivalent of the following (incorrect) code:
From what I gathered, this is only valid if client code casts the returned pointer back to a char. Note that I'm aware of the alignment issues, but this is just a simplified example.
From this discussion with Linus I take it I should disable the no aliasing optimization for the memory lib, but most of the code is templated so I should disable that optimization for every client of the memory lib. From that same discussion understand that the gain in performance and code size is very small to be generous. Do you think I should go ahead and disable said optimization? If so, will I find a way to do the same on compilers other than gcc (ie: Visual Studio), or will I end up with non-standard unportable code?
To my understanding, void* can be casted to something else only if the original variable holding the pointer to void has not been casted to something else yet. So:
void* myMem = malloc(sizeof(int) * 5);
int* a = (int*) myMem; // OK
short int* b = (short int*) myMem; //WRONG
Is this correct?
If so, writing a stack-based allocator is impossible, or is there any technique I don't know of to achieve that? I'd like to get the equivalent of the following (incorrect) code:
void* StackAlloc(int size) {
static char mem[64];
static int used = 0;
void* ret = mem + used;
used += size;
return ret;
}
From what I gathered, this is only valid if client code casts the returned pointer back to a char. Note that I'm aware of the alignment issues, but this is just a simplified example.
From this discussion with Linus I take it I should disable the no aliasing optimization for the memory lib, but most of the code is templated so I should disable that optimization for every client of the memory lib. From that same discussion understand that the gain in performance and code size is very small to be generous. Do you think I should go ahead and disable said optimization? If so, will I find a way to do the same on compilers other than gcc (ie: Visual Studio), or will I end up with non-standard unportable code?