(Wasn't sure about the title of my post, apologies for the poor title). I've implemented the following piece of code:
#include <iostream>
#include <algorithm>
using namespace std;
class MyIntVector {
public:
MyIntVector() {
m_size = 10;
m_mem = new int[m_size];
for(auto i = 0; i < size(); ++i)
m_mem[i] = 0;
}
MyIntVector(int size) {
m_size = size;
m_mem = new int[m_size];
}
MyIntVector(const MyIntVector& v) {
m_mem = new int[v.size()];
m_size = v.size();
for(auto i = 0; i < v.size(); ++i)
m_mem[i] = v[i];
}
MyIntVector(MyIntVector&& v) {
cout << "Calling move constructor" << std::endl;
m_size = v.size();
m_mem = v.m_mem;
v.m_mem = nullptr;
delete [] v.m_mem;
}
int size() const {return m_size;}
int& operator[](int i) { return m_mem[i];}
int operator[](int i) const { return m_mem[i];}
friend ostream& operator<<(ostream& os, const MyIntVector& v);
protected:
int * getMemPtr() {return m_mem;}
private:
int m_size;
int *m_mem;
};
ostream &operator<<(ostream &os, const MyIntVector &v) {
for (auto i = 0; i < v.size(); ++i)
os << v[i] << " ";
return os;
}
void linear_init(MyIntVector& v) {
for(auto i = 0; i < v.size(); ++i)
v[i] = i + 1;
}
int main(int argc, char** argv) {
MyIntVector&& my_v_2 = MyIntVector(20); //binding R-value to R-value reference
MyIntVector my_v_3(my_v_2);
return 0;
}
In the main specifically I'm initializing an r-value reference, and later I'm using it to initialize another object. I was expecting however the move constructor to be called, but the copy constructor is called instead, can anyone explain me why?
(It is just some test code to understand move semantics and r-value references).
Aucun commentaire:
Enregistrer un commentaire