#include <iostream>
#include <vector>
class Car{
public:
int weight;
Car(int weight): weight(weight){
};
Car(const Car& other){
std::cout<<"copied!"<<std::endl;
this->weight=other.weight;
}
};
int main() {
std::vector<Car> vec;
vec.push_back(Car(1));
return 0;
}
In the code above, somehow when I push Car(1) onto vec, the copy constructor in the Car class is called. Why is the copy constructor called? I'm not copying anything here.
You are copying since your Car struct does not implement move semantics. The copy is from the temporary you built with Car(1) to the object created in the vector. Using emplace_back to directly construct the object in the vector without the temporary object will prevent this.
#include <iostream>
#include <vector>
struct Car {
int weight;
Car(int weight) : weight(weight) { }
Car(const Car& other) : weight(other.weight) {
std::cout << "copied!\n";
}
};
int main() {
std::vector<Car> vec;
vec.emplace_back(1);
}
Note that even using emplace_back you may still see copy constructors called if the vector has to reallocate. This may be avoided by judicious use of reserve.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With