examples

Toy examples in single C files.
git clone git://henryandlizzy.uk/examples
Log | Files | Refs

mmallocator.cpp (1047B)


      1 #include <vector>
      2 #include <iostream>
      3 
      4 using namespace std;
      5 
      6 template <typename T>
      7 struct mmallocator
      8 {
      9 	using value_type = T;
     10 	mmallocator()
     11 	{
     12 		cout << __PRETTY_FUNCTION__ << '\n';
     13 	}
     14 	template <typename U> constexpr mmallocator(const mmallocator<U>&) noexcept
     15 	{}
     16 	[[nodiscard]] T* allocate(std::size_t const n)
     17 	{
     18 		if (n > std::size_t(-1) / sizeof(T))
     19 			throw std::bad_alloc();
     20 
     21 		if (auto p = static_cast<T*>(std::malloc(n*sizeof(T))))
     22 			return p;
     23 
     24 		throw std::bad_alloc();
     25 	}
     26 	void deallocate(T* p, std::size_t) noexcept
     27 	{
     28 		std::free(p);
     29 	}
     30 };
     31 
     32 template <class T, class U>
     33 bool operator==(const mmallocator<T>&, const mmallocator<U>&)
     34 {
     35 	return true;
     36 }
     37 
     38 template <class T, class U>
     39 bool operator!=(const mmallocator<T>&, const mmallocator<U>&)
     40 {
     41 	return false;
     42 }
     43 
     44 int main()
     45 {
     46 	mmallocator<char const*> mm;
     47 
     48 	std::vector<char const*, mmallocator<char const*>> v(mm);
     49 	std::vector<char const*, mmallocator<char const*>> v2(mm);
     50 
     51 	v.push_back("Hello");
     52 	v.push_back("World");
     53 
     54 	for (auto const s : v)
     55 		cout << s << '\n';
     56 
     57 	return 0;
     58 }