jeudi 4 juillet 2019

How do I generate objects in std::vector and without copy?

There is a student class

class Student
{
public:
    inline static int current_id_max = 0;
    int id = 0;
    string name;
public:
    Student()
    {
        id = (++current_id_max);
        cout << "Student constructor\n";
    }
    Student(const string& _name)
    {
        name = _name;
        id = (++current_id_max);
        cout << "Student constructor: " << _name << endl;
    }
    Student(const Student& o)
    {
        name = o.name;
        id = (++current_id_max);
        cout << "Student constructor copy: " << name << endl;
    }
    ~Student() { cout << "Student destructor: " << name << endl; }
};

I want to create 5 students with parameters into a vector,

std::vector<Student> school = 
    { Student("Tom"), Student("Mike"),Student("Zhang"), Student("Wang"), Student("Li")};

There will be 5 Student constructor: name and 5 Student constructor copy: name.

What can I do to avoid the useless copying?

Aucun commentaire:

Enregistrer un commentaire