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