Guest User

Untitled

a guest
Jun 21st, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.31 KB | None | 0 0
  1. /*************************** SafeArray.cpp *********************************
  2. * Author: Agner Fog
  3. * Date created: 2008-06-12
  4. * Last modified: 2008-06-12
  5. * Description:
  6. * Template class for array with bounds checking
  7. *
  8. * The latest version of this file is available at:
  9. * www.agner.org/optimize/cppexamples.zip
  10. * (c) 2008 GNU General Public License www.gnu.org/copyleft/gpl.html
  11. *******************************************************************************
  12. *
  13. * SafeArray defines an array with bounds checking.
  14. *
  15. * The size is defined at compile time. The elements in the array can be of
  16. * any type that do not require a constructor or destructor.
  17. *
  18. * An example of how to use SafeArray is provided at the end of this file.
  19. *
  20. ******************************************************************************/
  21.  
  22. /******************************************************************************
  23. Header part. Put this in a .h file:
  24. ******************************************************************************/
  25.  
  26. #include <memory.h> // For memcpy and memset
  27. #include <stdio.h> // Needed for example only
  28.  
  29.  
  30. // Template for safe array with bounds checking
  31. template <typename T, unsigned int N> class SafeArray {
  32. protected:
  33. T a[N]; // Array with N elements of type T
  34. public:
  35. // Constructor
  36. SafeArray() {
  37. memset(a, 0, sizeof(a)); // Initialize array to zero
  38. }
  39. // Return the size of the array
  40. int Size() const {
  41. return N;
  42. }
  43. // Safe [] array index operator
  44. T & operator[] (unsigned int i) {
  45. if (i >= N) {
  46. // Index out of range. The next line provokes an error.
  47. // You may insert any other error reporting here:
  48. return *(T*)0; // Return a null reference to provoke error
  49. }
  50. // No error
  51. return a[i]; // Return reference to a[i]
  52. }
  53. };
  54.  
  55.  
  56. /******************************************************************************
  57. Example part. Remove this from final application:
  58. ******************************************************************************/
  59.  
  60. int main() {
  61.  
  62. // Declare a safe array of 20 float's
  63. SafeArray<float, 10> list;
  64.  
  65. // Output all elements
  66. for (int i = 0; i < list.Size(); i++) {
  67. printf("\n%8.3f", list[i]);
  68. }
  69.  
  70. return 0;
  71. }
Add Comment
Please, Sign In to add comment