EVAP2

<Memoria>

Los elementos de memoria
Este encabezado define los servicios generales para la gestión de memoria dinámica:


 
ejemplos en c++:
// custom allocator example
#include <cstddef>
#include <iostream>
#include <memory>
#include <vector>

template <class T>
struct custom_allocator {
  typedef T value_type;
  custom_allocator() noexcept {}
  template <class U> custom_allocator (const custom_allocator<U>&) noexcept {}
  T* allocate (std::size_t n) { return static_cast<T*>(::new(n*sizeof(T))); }
  void deallocate (T* p, std::size_t n) { ::delete(p); }
};

template <class T, class U>
constexpr bool operator== (const custom_allocator<T>&, const custom_allocator<U>&) noexcept
{return true;}

template <class T, class U>
constexpr bool operator!= (const custom_allocator<T>&, const custom_allocator<U>&) noexcept
{return false;}

int main () {
  std::vector<int,custom_allocator<int>> foo = {10,20,30};
  for (auto x: foo) std::cout << x << " ";
  std::cout << '\n';
  return 0;
}
 
2)
// make_shared example
#include <iostream>
#include <memory>

int main () {

  std::shared_ptr<int> foo = std::make_shared<int> (10);
  // same as:
  std::shared_ptr<int> foo2 (new int(10));

  auto bar = std::make_shared<int> (20);

  auto baz = std::make_shared<std::pair<int,int>> (30,40);

  std::cout << "*foo: " << *foo << '\n';
  std::cout << "*bar: " << *bar << '\n';
  std::cout << "*baz: " << baz->first << ' ' << baz->second << '\n';

  return 0;
} 





No hay comentarios:

Publicar un comentario