1

I ask knowing the difference between these two implementations :

  std::vector<std::unique_ptr<Character>> characters;

  characters.emplace_back(new Character("Character", 100));

And

   std::vector<std::unique_ptr<Character>> characters;

   characters.emplace_back(std::make_unique<Character> ("Character", 100));

For Character's type example (in case needing details) :

class Character{

 public:
     Character(){
         m_name="";
         m_life=0;
         }
     Character(std::string name, int life):m_name(name), m_life(life){
          position= new AdaptPosition{0,0};
     }
     virtual~Character(){delete position;}

      void advance(int const& x, int const& y){
         advancex(x);
         advancey(y);
      }

      void advancex(int x){
          position->advancedx(x);
      }
      void advancey(int y){
          position->advancedy(y);
      }

      void getPosition(){
          position->show();
      }

      friend std::ostream& operator<<(std::ostream& out, Character& character){

         out << character.m_name << "With life :"<< character.m_life << " In position :"<< std::endl;
         character.getPosition();

         return out;
      }
 protected:
    std::string m_name;
    int m_life;

    AdaptPosition *position;


};

Following this example, is there any diffrence when it compiles (Assembly view), or is there different Assembly instructions between the two ways ?

rekkalmd
  • 171
  • 1
  • 12
  • In case it matters, how is `Character` defined? Is it trivially copyable, or does it have a `std::string` member or something. – Peter Cordes May 31 '20 at 02:29
  • 7
    If `emplace_back` throws an exception (e.g. fails to allocate sufficient memory), then the first version would leak an instance of `Character` while the second version would not. – Igor Tandetnik May 31 '20 at 02:31
  • Appreciate the answer, if you may, besides handling manually the exception (`new Character(args)` 's case), is it safe to let it like that ? – rekkalmd May 31 '20 at 03:00

0 Answers0