Zha*_*ang 8 c++ performance stl c++11
有一个学生班
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; }
};
Run Code Online (Sandbox Code Playgroud)
我想创建5个带有参数的学生向量
std::vector<Student> school =
{ Student("Tom"), Student("Mike"),Student("Zhang"), Student("Wang"), Student("Li")};
Run Code Online (Sandbox Code Playgroud)
将有5 Student constructor: name
和5 Student constructor copy: name
。
我该怎么做才能避免无用的复制?
R S*_*ahu 10
我建议以下内容:
std::vector::emplace_back
向其中添加元素。一个完整的例子:
#include <iostream>
#include <vector>
#include <string>
class Student
{
public:
inline static int current_id_max = 0;
int id = 0;
std::string name;
public:
Student()
{
id = (++current_id_max);
std::cout << "Student constructor\n";
}
Student(const std::string& _name)
{
name = _name;
id = (++current_id_max);
std::cout << "Student constructor: " << _name << std::endl;
}
Student(const Student& o)
{
name = o.name;
id = (++current_id_max);
std::cout << "Student constructor copy: " << name << std::endl;
}
~Student() { std::cout << "Student destructor: " << name << std::endl; }
};
int main()
{
std::vector<Student> school;
school.reserve(5);
school.emplace_back("Tom");
school.emplace_back("Mike");
school.emplace_back("Zhang");
school.emplace_back("Wang");
school.emplace_back("Li");
}
Run Code Online (Sandbox Code Playgroud)
我测试中的输出:
#include <iostream>
#include <vector>
#include <string>
class Student
{
public:
inline static int current_id_max = 0;
int id = 0;
std::string name;
public:
Student()
{
id = (++current_id_max);
std::cout << "Student constructor\n";
}
Student(const std::string& _name)
{
name = _name;
id = (++current_id_max);
std::cout << "Student constructor: " << _name << std::endl;
}
Student(const Student& o)
{
name = o.name;
id = (++current_id_max);
std::cout << "Student constructor copy: " << name << std::endl;
}
~Student() { std::cout << "Student destructor: " << name << std::endl; }
};
int main()
{
std::vector<Student> school;
school.reserve(5);
school.emplace_back("Tom");
school.emplace_back("Mike");
school.emplace_back("Zhang");
school.emplace_back("Wang");
school.emplace_back("Li");
}
Run Code Online (Sandbox Code Playgroud)