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: 306904804
Change-Id: I3122b32b993c05fdebc16dc7b2493ce800dd6678
This commit is contained in:
Robert David 2020-04-16 12:56:27 -07:00 committed by TensorFlower Gardener
parent 869fc5f111
commit bb86c3c1f0
2 changed files with 9 additions and 8 deletions

View File

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

View File

@ -32,14 +32,15 @@ class BuiltinDataAllocator {
virtual void* Allocate(size_t size) = 0;
virtual void Deallocate(void* data) = 0;
// 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.
// 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.
template <typename T>
T* AllocatePOD() {
static_assert(std::is_pod<T>::value, "Builtin data structure must be POD.");
return static_cast<T*>(this->Allocate(sizeof(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;
}
virtual ~BuiltinDataAllocator() {}