c++ - Why is it better to use std::make_* instead of the constructor? -


there functions in stl start make_ prefix std::make_pair, std::make_shared, std::make_unique etc. why better practice use them instead of using constructor ?

auto pair2 = std::pair< int, double >( 1, 2.0 ); auto pair3 = std::make_pair( 1, 2.0 );  std::shared_ptr< int > pointer1 = std::shared_ptr< int >( new int( 10 ) ); std::shared_ptr< int > pointer2 = std::make_shared< int >( 10 ); 
  • i see these functions make code little shorter, ?
  • are there other advantages ?
  • are these functions safer use ?

aside benefit of enabling argument deduction (as mentioned in other answers), there other benefits.

std::make_pair<t1, t2> takes care not return std::pair<t1, t2>. if pass in value using std::ref, returned pair won't store std::reference_wrapper, store reference.

std::make_shared can combine allocations. shared_ptr needs place hold things refcount, weak pointer list, etc. cannot stored in shared_ptr directly. these can combined object being created, in 1 larger block rather in 2 separate blocks.

std::make_shared , std::make_unique both make sure no object gets left behind if exceptions thrown. if call function f(std::shared_ptr<int>(new int), std::shared_ptr<int>(new int)), it's possible compiler first allocates 2 int objects, , constructs 2 shared_ptr<int> objects. if second allocation fails, , no shared_ptr<int> object set yet release memory on destruction, have memory leak. std::make_shared , std::make_unique combine allocation of int , construction of std::shared_ptr<int> in function call, , other allocation of int , other construction of std::shared_ptr<int> in function call. function calls cannot overlap, if second allocation fails, there shared pointer destroyed, undoing first allocation well.


Comments

Popular posts from this blog

rewrite asp to php based on asp query -

android - questions about switching from C2DM to GCM -

visual studio 2010 - Error on RDLC Expression -