I have the class below and tried to add copy and move constructor and assignment operator. My goal is to have least amount of copy and be as optimized as possible.
I expect the vectors to be filled in place, that is no copy constructors be called while creating the vector. What am I doing wrong and how to force it to use move constructor or assignment?
#include <iostream>
#include <concepts>
#include <vector>
template<typename T>
requires std::is_arithmetic_v<T>
class Data {
private :
T mA = 0;
T mB = 0;
public:
Data(const T& data) : mA{data}{ // from single T
std::cout << "Constructed Data with: " << mA << ", " << mB << std::endl;
}
Data(const Data<T>& other) : mA{other.mA}, mB{other.mB} {
std::cout << "COPY Constructed Data with: " << mA << ", " << mB << std::endl;
}
Data(Data<T>&& other) : mA{other.mA}, mB{other.mB} {
std::cout << "MOVE Constructed Data with: " << mA << ", " << mB << std::endl;
}
Data(const std::initializer_list<T>& list) {
std::cout << "Constructed Data with list: ";
if(list.size() >= 2) {
mA = *list.begin();
mB = *(list.begin() + 1);
std:: cout << mA << ", " << mB << std::endl;
}
}
~Data() {
std::cout << "Destructed: " << mA << ", " << mB << std::endl;
}
const Data operator=(const Data& other) {
mA = other.mA;
mB = other.mB;
return *this;
}
Data operator=(Data&& other) {
mA = other.mA;
mB = other.mB;
return *this;
}
};
int main() {
std::cout << "** With initilizer_list **" << std::endl;
{
auto vec = std::vector<Data<int>>{{1,1}, {2,2}};
}
std::cout << "\n**With element**" << std::endl;
{
auto vec = std::vector<Data<int>>{1,2};
}
std::cout << "\n**With push**" << std::endl;
{
auto vec = std::vector<Data<int>>();
vec.push_back(1);
vec.push_back(2);
}
}
Output:
** With initilizer_list ** Constructed Data with list: 1, 1 Constructed Data with list: 2, 2 COPY Constructed Data with: 1, 1 COPY Constructed Data with: 2, 2 Destructed: 2, 2 Destructed: 1, 1 Destructed: 1, 1 Destructed: 2, 2 **With element** Constructed Data with: 1, 0 Constructed Data with: 2, 0 COPY Constructed Data with: 1, 0 COPY Constructed Data with: 2, 0 Destructed: 2, 0 Destructed: 1, 0 Destructed: 1, 0 Destructed: 2, 0 **With push** Constructed Data with: 1, 0 MOVE Constructed Data with: 1, 0 Destructed: 1, 0 Constructed Data with: 2, 0 MOVE Constructed Data with: 2, 0 COPY Constructed Data with: 1, 0 Destructed: 1, 0 Destructed: 2, 0 Destructed: 1, 0 Destructed: 2, 0