fork download
  1. #include<iostream>
  2. #include<type_traits>
  3.  
  4. // Think that another thread reads this array
  5. template<typename T, size_t M>
  6. inline void zero_func(volatile T (&arr)[M]) {
  7. for(auto &i : arr) i = 0;
  8. }
  9.  
  10. template<typename T, size_t M>
  11. inline void zero_func(volatile T *ptr) {
  12. zero_func(reinterpret_cast<volatile T (&)[M]>(*ptr));
  13. }
  14.  
  15. template<typename T, size_t M>
  16. inline void compare_types(volatile T (&arr)[M]) {
  17. volatile char a[M] = {0};
  18. volatile char *b = a;
  19. volatile char * volatile c = a;
  20. decltype(a) d;
  21. std::cout << std::boolalpha;
  22. std::cout << "Which type is equivalent to: volatile char a[M]?" << std::endl;
  23. std::cout << "volatile char *b: \t\t" << std::is_same<decltype(a), decltype(b)>::value << std::endl;
  24. std::cout << "volatile char * volatile c: \t" << std::is_same<decltype(a), decltype(c)>::value << std::endl;
  25. std::cout << "decltype(a): \t\t\t" << std::is_same<decltype(a), decltype(d)>::value << std::endl;
  26.  
  27. // volatile char a[100] and volatile T (&arr)[M] are same types, excluding reference
  28. typedef decltype(arr) T_vol_ref;
  29. typedef typename std::remove_reference<T_vol_ref>::type T_vol;
  30. std::cout << "volatile T (&arr)[M]: \t\t" << std::is_same<decltype(a), T_vol>::value << std::endl;
  31. }
  32.  
  33. int main() {
  34. char for_zero[100] = {1};
  35.  
  36. // secure zero
  37. zero_func<char, 100>(for_zero);
  38. std::cout << (unsigned)for_zero[0] << std::endl;
  39.  
  40. char *for_zero2 = new char[100];
  41. for_zero2[0] = 1;
  42. zero_func<char, 100>(for_zero2);
  43. std::cout << (unsigned)for_zero2[0] << std::endl;
  44. delete for_zero2;
  45.  
  46. compare_types(for_zero);
  47.  
  48. return 0;
  49. }
Success #stdin #stdout 0s 3028KB
stdin
Standard input is empty
stdout
0
0
Which type is equivalent to: volatile char a[M]?
volatile char *b: 		false
volatile char * volatile c: 	false
decltype(a): 			true
volatile T (&arr)[M]: 		true