It is only necessary types to be trivially destructible in AllocatePOD. Also rename the function, as it's not allocating PODs any more.

Use placement new to actually create the allocated object (just static_casting to the type is undefined behavior even if the default constructor is trivial, although works fine with most compilers).

PiperOrigin-RevId: 306975186
Change-Id: I7fb693df63920a200b8c81e93521425638b8ca53
This commit is contained in:
Tiezhen WANG 2020-04-16 20:36:54 -07:00 committed by TensorFlower Gardener
parent 7bc093f765
commit f3369e24bb
2 changed files with 8 additions and 9 deletions

View File

@ -49,7 +49,7 @@ class SafeBuiltinDataAllocator {
template <typename T>
BuiltinDataPtr<T> Allocate() {
return BuiltinDataPtr<T>(allocator_->AllocateStruct<T>(),
return BuiltinDataPtr<T>(allocator_->AllocatePOD<T>(),
BuiltinDataDeleter(allocator_));
}

View File

@ -32,15 +32,14 @@ class BuiltinDataAllocator {
virtual void* Allocate(size_t size) = 0;
virtual void Deallocate(void* data) = 0;
// Allocate a structure, but make sure it is trivially destructible. The
// reason we do this, is that Interpreter's C extension part will take
// ownership so destructors will not be run during deallocation.
// Allocate a structure, but make sure it is a POD structure that doesn't
// require constructors to run. The reason we do this, is that Interpreter's C
// extension part will take ownership so destructors will not be run during
// deallocation.
template <typename T>
T* AllocateStruct() {
static_assert(std::is_trivially_destructible<T>::value,
"Builtin data structure must be trivially destructible.");
void* allocated_memory = this->Allocate(sizeof(T));
return new (allocated_memory) T;
T* AllocatePOD() {
static_assert(std::is_pod<T>::value, "Builtin data structure must be POD.");
return static_cast<T*>(this->Allocate(sizeof(T)));
}
virtual ~BuiltinDataAllocator() {}