c++ - CppUnit - how use unique_ptr in setUp() -
the code taken http://cppunit.sourceforge.net/doc/cvs/cppunit_cookbook.html here creating pointers on heap , deleted them in teardown()
private: complex *m_10_1, *m_1_1, *m_11_2; public: void setup() { m_10_1 = new complex( 10, 1 ); m_1_1 = new complex( 1, 1 ); m_11_2 = new complex( 11, 2 ); } void teardown() { delete m_10_1; delete m_1_1; delete m_11_2; } void testequality() { cppunit_assert( *m_10_1 == *m_10_1 ); cppunit_assert( !(*m_10_1 == *m_11_2) ); } void testaddition() { cppunit_assert( *m_10_1 + *m_1_1 == *m_11_2 ); } };
but if use unique_ptr instead. lifetime of unique_ptr? deleted @ end of setup()? , should create instance in every test? possible avoid code duplication unique_ptr?
private: std::unique_ptr<complex> m_10_1; std::unique_ptr<complex> m_1_1; std::unique_ptr<complex> m_11_2; public: void setup() { m_10_1.reset(new complex(10, 1)); m_1_1.reset(new complex(1, 1)); m_11_2.reset(new complex(11, 2)); } void teardown() { } void test1() { // tests usage of ptr. m_10_1.reset(new complex(10, 1)); // should here insted setup() ?? } void test2() { // tests usage of ptr. m_10_1.reset(new complex(10, 1)); // should here insted setup() ?? } };
those exist long containing object exists. unique_ptr's destructor called implicitly when containing object destroyed. whenever complexnumbertest
destroyed, heap allocated objects well.
if have access c++14 consider using std::make_unique.
Comments
Post a Comment