"Alf P. Steinbach" <al***@start.no wrote in message
news:xeOdnY77pZ L6mr7VnZ2dnUVZ_ gSdnZ2d@comnet. ..
>* Chris Thomasson:
>"Alf P. Steinbach" <al***@start.no wrote in message
news:cI******* *************** ********@posted .comnet...
>>* Chris Thomasson:
Does this program produce any undefined-behavior:
http://pastebin.com/m5eb3c81a
?
Yes,
*pregion = (Region*)0x1234 8765
is formally UB.
Is that the only thing you can find?
If you want a more thorough discussion, post the code, and explain what
you're concerned about. Then others will probably jump on it. It's The
Way(TM).
Okay:
/*************** *************** *************** *************** **********/
#include <cstdio>
#include <cstddef>
#include <cassert>
#include <new>
// Imagine there is a "special" allocator interface...
// I will just use ::operator new/delete for place holders
namespace Allocator {
struct Region;
static void* MemRequest(
Region** pregion,
std::size_t size
) {
*pregion = (Region*)0x1234 8765;
return ::operator new(size);
}
static void MemRelease(
Region* region,
void* ptr,
std::size_t size
) {
assert(region == (Region*)0x1234 8765);
::operator delete(ptr);
}
}
// Can I use the above allocator interface like this:
template<typena me T>
struct AllocatorBlock {
unsigned char mBuffer[sizeof(T)];
Allocator::Regi on* mRegion;
static void* MemRequest() {
Allocator::Regi on* region;
AllocatorBlock* const block = (AllocatorBlock *)
Allocator::MemR equest(®ion, sizeof(T));
block->mRegion = region;
return block->mBuffer;
}
static void MemRelease(void * ptr) {
AllocatorBlock* const block = (AllocatorBlock *)ptr;
Allocator::MemR elease(block->mRegion, ptr, sizeof(T));
}
};
struct MyObject {
int const State;
MyObject(int state) : State(state) {}
// special per-object new/delete overload...
void* operator new(std::size_t size) {
return AllocatorBlock< MyObject>::MemR equest();
}
void operator delete(void* ptr) {
AllocatorBlock< MyObject>::MemR elease(ptr);
}
};
#define OBJECTS 10
int main() {
int i;
MyObject* objs[OBJECTS] = { NULL };
for (i = 0; i < OBJECTS; ++i) {
objs[i] = new MyObject(i + 1);
std::printf("(% p/%d) - Create\n", (void*)objs[i], objs[i]->State);
}
std::puts("-----------------------------------------");
for (i = 0; i < OBJECTS; ++i) {
std::printf("(% p/%d) - Destroy\n", (void*)objs[i], objs[i]->State);
delete objs[i];
}
std::puts("\n\n \n_____________ _______________ ______\
_______________ __________\nPre ss <ENTERto exit...");
std::getchar();
return 0;
}
/*************** *************** *************** *************** **********/