utility_tests.cpp

Go to the documentation of this file.
00001 
00012 #include <stdlib.h>
00013 #include <new>
00014 #include <iostream>
00015 
00016 #include "utility.h"
00017 #include "op_exception.h"
00018 
00019 using namespace std;
00020 
00021 static int nb_new;
00022 static int nb_new_array;
00023 
00024 void* operator new(size_t size) throw(bad_alloc)
00025 {
00026     nb_new++;
00027     return malloc(size);
00028 }
00029 
00030 void* operator new[](size_t size) throw(bad_alloc)
00031 {
00032     nb_new_array++;
00033     return malloc(size);
00034 }
00035 
00036 void operator delete(void * p) throw()
00037 {
00038     nb_new--;
00039     if (p)
00040         free(p);
00041 }
00042 
00043 void operator delete[](void * p) throw()
00044 {
00045     nb_new_array--;
00046     if (p)
00047         free(p);
00048 }
00049 
00050 
00051 void check_alloc()
00052 {
00053     if (nb_new) {
00054         cerr << "new(size_t) leak\n";
00055         exit(EXIT_FAILURE);
00056     }
00057 
00058     if (nb_new_array) {
00059         cerr << "new[](size_t) leak\n";
00060         exit(EXIT_FAILURE);
00061     }
00062 }
00063 
00064 
00065 struct A {};
00066 
00067 template <typename Throw, typename Catch>
00068 void throw_tests()
00069 {
00070     scoped_ptr<A> a(new A);
00071     try {
00072         scoped_ptr<A> a(new A);
00073         throw Throw("");
00074     }
00075     catch (Catch const &) {
00076     }
00077 }
00078 
00079 
00080 template <typename Throw, typename Catch>
00081 void throw_tests(bool)
00082 {
00083     scoped_array<A> b(new A[10]);
00084     try {
00085         scoped_array<A> a(new A[10]);
00086         throw Throw("");
00087     }
00088     catch (Catch const &) {
00089     }
00090 }
00091 
00092 
00093 void tests_new()
00094 {
00095     throw_tests<op_fatal_error, op_fatal_error>();
00096     throw_tests<op_fatal_error, op_exception>();
00097     throw_tests<op_runtime_error, op_runtime_error>();
00098     throw_tests<op_runtime_error, runtime_error>();
00099     throw_tests<op_fatal_error, op_fatal_error>(true);
00100     throw_tests<op_fatal_error, op_exception>(true);
00101     throw_tests<op_runtime_error, op_runtime_error>(true);
00102     throw_tests<op_runtime_error, runtime_error>(true);
00103 }
00104 
00105 
00106 int main()
00107 {
00108     try {
00109         tests_new();
00110         check_alloc();
00111     }
00112     catch (...) {
00113         cerr << "unknown exception\n";
00114         return EXIT_FAILURE;
00115     }
00116 
00117     return EXIT_SUCCESS;
00118 }

Generated on 8 Nov 2012 for Oprofile by  doxygen 1.6.1