c++ - What happen if exception's thrown during allocation? -


i have following function template:

template<typename t> void init(std::vector<t>& v, int min, int max) {     for(int = min; <= max; i++)         v.push_back(new t()); } 

which use function follows:

void foo() {     std::vector v;     init(v, 10, 20);     //something else } 

what happens if exception thrown during initialization of object of type t in function init?

do memory leak in case or other kind of ub? if so, how can prevent it?

if memory allocation fail, std::bad_alloc exception. if there exception during execution of construction of type t, should handled in constructor of type t using try catch block.

if std::vector::push_back failed after creation of object using new operator, there possibility of memory leak since newly generated raw pointer not yet part of vector.since creating vector of raw pointers generated using new operator, , should call delete on contents of vector part of proper clean up. std::vector<> destructor cleans pointers not objects of type t.

to resolve raw pointer issue, can depend on std::shared_ptr or std::unique_ptr in place of raw pointer if have c++11 compiler


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -