mardi 20 avril 2021

Why does copy constructor is called in here? [duplicate]

In the following example there is a Movie object and Movies object which contain a collection of movies.

class Movie {
 private:
  string name;
  string movie_rating;
  unsigned int watched;

 public:
  Movie(const string&, const string&, unsigned int);
  Movie(const Movie&);
  Movie(Movie&&);

  // SETTERS AND GETTERS
  const string& getName() const;
  void setName(const string& value);

  const string& getMovie_rating() const;
  void setMovie_rating(const string& value);

  unsigned int getWatched() const;
  void setWatched(unsigned int value);

  //Increment Function

  void increment_watched();
};
class Movies {
 private:
  vector<Movie> collection;

 public:
  Movies();

  // Movies Functions
  void add_movie(const string&, const string&, unsigned int);

  void increment_movie(const string&);

  void display_movies() const;
  const vector<Movie>& getCollection() const;
};

When I add a movie through add_movie function, in the terminal a copy constructor is called even though I'm using emplace_back which creates the object in the vector itself.

void Movies::add_movie(const string &name, const string &movie_rating,
                       unsigned int watched) {
  collection.emplace_back(name, movie_rating, watched);
}

Here is the terminal output after adding three movies using add_movie function:-

Movies Collection Constructor
Movie Constructor
Movie Constructor
Copy
Movie Constructor
Copy
Copy
Name:- Big
Movie Rating:- PG-13
Number of times watched:- 2
Name:- Star Wars
Movie Rating:- PG
Number of times watched:- 5
Name:- Cinderella
Movie Rating:- PG
Number of times watched:- 7

Why was copy constructor not called when I used list, and which is better in this example list or vectors?

Aucun commentaire:

Enregistrer un commentaire