在学习C++和所有关于构造函数(复制、移动)的时候,我想知道什么是正确/智能/有效的方法。下面的场景:我有一个包含标题、分级和计数器的类Movie。每次我实例化该类的对象时,我都希望将该对象放入一个对象数组(称为电影)中。因此,如果我看了3部电影,我的数组将包含Movie类的3个实例。因为我的电影类不包含原始指针,所以我想知道使用copy还是move将特定的电影添加到我的集合中是否会有性能上的差异。我希望我的想法是清晰的,以便更好地理解以下代码。希望有人能开导我。谢谢,
Mingw-w64版本8.1.0,Win10,VSCode:
#include <iostream>
#include <vector>
using std::cout;
using std::endl;
using std::string;
using std::vector;
class Movie
{
private:
string movieName;
int movieRating;
int movieCounter;
public:
string getName();
Movie(string movieNameVal="None", int movieRatingVal=0);
Movie(const Movie &source);
Movie(Movie &&source);
~Movie();
};
Movie::Movie(string movieNameVal, int movieRatingVal)
: movieName(movieNameVal), movieRating(movieRatingVal) // Equivalent to movieName = movieNameVal; movieRating = movieRatingVal;
{
cout << "Constructor called" << endl;
}
// Copy constructor
Movie::Movie(const Movie &source)
: Movie(source.movieName, source.movieRating)
{
cout << "Copy constructor called" << endl;
}
// Move constructor
Movie::Movie(Movie &&source)
: movieName(source.movieName), movieRating(source.movieRating)
{
cout << "Move constructor called" << endl;
}
Movie::~Movie()
{
cout << "Destructor called" << endl;
}
int main()
{
{
vector<Movie> Movies1;
cout << "------------Movies1: Copy constructor version------------" << endl;
Movie movie1("Terminator 1", 5);
Movies1.push_back(movie1);
}
cout << endl;
cout << endl;
cout << endl;
{
vector<Movie> Movies2;
string namex = "Terminator 2";
int ratingx = 5;
cout << "------------Movies2: Move constructor version------------" << endl;
Movies2.push_back(Movie(namex, ratingx));
}
return 0;
}发布于 2021-04-08 04:01:25
当您通过复制或移动特定类的对象实例来追加向量时,您会问到性能上的差异。首先,你总是可以测量的!我认为大部分时间都花在向量重新分配它的capacity()上,所以当你知道要插入的对象的数量时,总是建议reserve()一些内存。
查看您的代码片段的输出:
------------Movies1: Copy constructor version------------
Constructor called
Constructor called
Copy constructor called
Destructor called
Destructor called
------------Movies2: Move constructor version------------
Constructor called
Move constructor called
Destructor called
Destructor called我想我已经看到了一个赢家。正如注释中所说,在您的特定类中,您可以让编译器生成默认构造函数;通常情况下,移动可能比复制更有效(参见更多here)。但是,请考虑以下第三种可能性:
Movies3.emplace_back(namex, ratingx);------------Movies3: emplace_back version------------
Constructor called
Destructor called那也不会太糟。
https://stackoverflow.com/questions/66992046
复制相似问题