ctorleak.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #include "main.h"
  2. #include <exception> // std::exception
  3. struct Foo
  4. {
  5. static Index object_count;
  6. static Index object_limit;
  7. int dummy;
  8. Foo() : dummy(0)
  9. {
  10. #ifdef EIGEN_EXCEPTIONS
  11. // TODO: Is this the correct way to handle this?
  12. if (Foo::object_count > Foo::object_limit) { std::cout << "\nThrow!\n"; throw Foo::Fail(); }
  13. #endif
  14. std::cout << '+';
  15. ++Foo::object_count;
  16. }
  17. ~Foo()
  18. {
  19. std::cout << '-';
  20. --Foo::object_count;
  21. }
  22. class Fail : public std::exception {};
  23. };
  24. Index Foo::object_count = 0;
  25. Index Foo::object_limit = 0;
  26. #undef EIGEN_TEST_MAX_SIZE
  27. #define EIGEN_TEST_MAX_SIZE 3
  28. void test_ctorleak()
  29. {
  30. typedef Matrix<Foo, Dynamic, Dynamic> MatrixX;
  31. typedef Matrix<Foo, Dynamic, 1> VectorX;
  32. Foo::object_count = 0;
  33. for(int i = 0; i < g_repeat; i++) {
  34. Index rows = internal::random<Index>(2,EIGEN_TEST_MAX_SIZE), cols = internal::random<Index>(2,EIGEN_TEST_MAX_SIZE);
  35. Foo::object_limit = rows*cols;
  36. {
  37. MatrixX r(rows, cols);
  38. Foo::object_limit = r.size()+internal::random<Index>(0, rows*cols - 2);
  39. std::cout << "object_limit =" << Foo::object_limit << std::endl;
  40. #ifdef EIGEN_EXCEPTIONS
  41. try
  42. {
  43. #endif
  44. if(internal::random<bool>()) {
  45. std::cout << "\nMatrixX m(" << rows << ", " << cols << ");\n";
  46. MatrixX m(rows, cols);
  47. }
  48. else {
  49. std::cout << "\nMatrixX m(r);\n";
  50. MatrixX m(r);
  51. }
  52. #ifdef EIGEN_EXCEPTIONS
  53. VERIFY(false); // not reached if exceptions are enabled
  54. }
  55. catch (const Foo::Fail&) { /* ignore */ }
  56. #endif
  57. }
  58. VERIFY_IS_EQUAL(Index(0), Foo::object_count);
  59. {
  60. Foo::object_limit = (rows+1)*(cols+1);
  61. MatrixX A(rows, cols);
  62. VERIFY_IS_EQUAL(Foo::object_count, rows*cols);
  63. VectorX v=A.row(0);
  64. VERIFY_IS_EQUAL(Foo::object_count, (rows+1)*cols);
  65. v = A.col(0);
  66. VERIFY_IS_EQUAL(Foo::object_count, rows*(cols+1));
  67. }
  68. VERIFY_IS_EQUAL(Index(0), Foo::object_count);
  69. }
  70. std::cout << "\n";
  71. }