Overview
Examples
Screenshots
Comparisons
Applications
Download
Documentation
Tutorials
Bazaar
Status & Roadmap
FAQ
Authors & License
Forums
Funding Ultimate++
Search on this site
Search in forums












SourceForge.net Logo
Home » U++ Library support » U++ Core » Doubt with Buffer<> of a trivially destructible type
Re: Doubt with Buffer<> of a trivially destructible type [message #61251 is a reply to message #61250] Sun, 15 December 2024 12:45 Go to previous messageGo to previous message
koldo is currently offline  koldo
Messages: 3437
Registered: August 2008
Senior Veteran
The solution for U++ could be any of these, applied to class Buffer<> functions Malloc() and Free():

- For C++ 17, just insert constexpr in the std::is_trivially_destructible check, to force it to work in compile time:
if constexpr (std::is_trivially_destructible<T>::value)


- In C++ it is a little more complicated as it requires a little of SFINAE. This way the std::is_trivially_destructible check works in compile time:

	template <typename U = T>
	typename std::enable_if<!std::is_trivially_destructible<U>::value>::type
	Malloc(size_t size) {
		void* p = MemoryAlloc(size * sizeof(U) + 16);
		*(size_t*)p = size;
		ptr = (U*)((byte*)p + 16);
	}
	template <typename U = T>
	typename std::enable_if<std::is_trivially_destructible<U>::value>::type
	Malloc(size_t size) {
		ptr = (U*)MemoryAlloc(size * sizeof(U));
	}

	template <typename U = T>
	typename std::enable_if<!std::is_trivially_destructible<U>::value>::type
	Free() {
		if (ptr) {
			void* p = (byte*)ptr - 16;
			size_t size = *(size_t*)p;
			Destroy(ptr, ptr + size);
			MemoryFree(p);
		}
	}
	template <typename U = T>
	typename std::enable_if<std::is_trivially_destructible<U>::value>::type
	Free() {
		if (ptr) {
			MemoryFree(ptr);
		}
	}


Best regards
IƱaki
 
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Previous Topic: How to respond when memory is exceeded
Next Topic: Stream Load serialization fired twice
Goto Forum:
  


Current Time: Sat Jun 07 14:02:22 CEST 2025

Total time taken to generate the page: 0.03687 seconds