Advertisement
Guest User

Untitled

a guest
Aug 22nd, 2017
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.61 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. // we define a class, that we will be constructing later
  4. class T
  5. {
  6. public:
  7.     float _z;
  8.     int _x, _y;
  9.  
  10.  
  11.     T(float z) : _z{z} {} // constructor with only one, float-type parameter
  12.     T(int x, int y) : _x{x}, _y{y} {} // constructor with two int parameters
  13. };
  14.  
  15.  
  16. // our array class
  17. class A
  18. {
  19. public:
  20.     int _count = 0; // how many elements are in the array
  21.     int _memory[256]; // memory for our objects - (256 * sizeof(T)) bytes wide
  22.  
  23.     void* operator[](int count) // returns the memory address of the count-th T element
  24.     {
  25.         return _memory + sizeof(T) * count; //begin of the memory + sizof(element) * element_count
  26.     }
  27.  
  28.     template <typename... Args> // variadic template definition
  29.     void emplace_back(Args&&... args)  // variadic arguments
  30.     {
  31.         // construction of object T with args-constructor-arguments on specified memory location
  32.         new (operator[](_count++)) T(std::forward<Args>(args)...);
  33.     }
  34. };
  35.  
  36. int main()
  37. {
  38.     A arr; // array declaration
  39.     arr.emplace_back(1, 3);  // constructing first object T{1, 3} on address memory[0]
  40.     arr.emplace_back(3.14f); // constructing second object T{3.14f} on address memory[sizeof(T) * 1]
  41.  
  42.     auto first = reinterpret_cast<T*>(&arr._memory[0]); // interpreting the memory as the object created (T) - first object
  43.     auto second = reinterpret_cast<T*>(&arr._memory[sizeof(T)]); // ^^ second object
  44.  
  45.     printf("x0=%d\ny0=%d\n", first->_x, first->_y); // reading the ints from first object
  46.     printf("z1=%f\n", second->_z); // reading z-value from the second object
  47.  
  48.     system("pause");
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement