c++11 - C++ Create objects in a try bloc then store them in a std::array -


i have player object can throw exception inside constructor, in main function i'm creating 2 player objects inside try block. want store these 2 players in std::array that:

try {   player p1(10, 10, ikazuchi);   player p2(70, 10, hibiki);   std::array<player, 2> players = {p1, p2}; } 

the problem wouldn't able use array outside of try block, , heard placing main code inside try block bad idea.

i can't declare std::array after try block because p1 , p2 no longer exist there.

i can solve problem std::vector, have read better use std::array when know size of array during compilation.

i create default constructor create objects fill them inside try block, seems more proper create in constructor.

what best practice that?

you can around issues using dynamic allocation or boost::optional<std::array<player, 2>>, real question is: should you? is, assume 1 of player objects fails construct , throws exception. players array after that? it's not in legal state, or @ least not in state you'd expect if no exception thrown.

there no problem having scope of try large. should cover exception prevent progressing. if don't physically having lot of source code there, move code function. might idea anyway: 1 function assumes goes well, , 1 chief responsibility handle errors.

and if have meaningful ways of continuing use players when objects inside in invalid state (constructor threw), can create array objects in state in first place (outside try block), , assign them inside try.

the question states don't want provide unneeded default constructor, claim either player belongs inside try, or player needs default constructor (or equivalent way of expressing "not initialised properly).


Comments

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -