Can someone help mend my understanding of std::move?
I thought that if an r-value reference goes out of scope what it references would too if it was assigned using the std::move operator. Why is that not the case in the below code?
#include<iostream>
using namespace std;
int main()
{
string one = "1 - one";
string two = "2 - two";
{
//not as expected
string & lValRef = one;
string && rValRef = std::move(two);
string newS(rValRef);
}
cout << "one : " << one << endl;
cout << "two : " << two << endl;
{
//as expected
string temp(std::move(one));
string tempAssignment;
tempAssignment = std::move(two);
}
cout << "one : " << one << endl;
cout << "two : " << two << endl;
return 0;
}
You can fiddle with it here.
I always thought using std::move was a way to leave objects in a 'deletable state'. So I was surprised that 'two' printed anything out the first time. Is there any use in creating a && r-value reference as I did ('rValRef')? [I understand that a std::move() would be required around my 'rValRef' for it to work as desired].
Below is my own code that I used to help me understand this better. Please play around with it if you desire :) Code here.
#include <iostream>
#include <vector>
using namespace std;
class SimpleClass {
friend ostream& operator<<(ostream & s,const SimpleClass & rhs);
private:
vector<char> data;
public:
SimpleClass(initializer_list<char> lst):data(lst.size()) {
copy(lst.begin(),lst.end(),data.begin());
}
SimpleClass(size_t dim = 0):data(dim){};
virtual ~SimpleClass() = default;
SimpleClass(const SimpleClass & rhs) = default;
SimpleClass & operator=(const SimpleClass & rhs) = default;
SimpleClass(SimpleClass && rhs):data(move(rhs.data)){};
SimpleClass & operator=(SimpleClass && rhs){
if (this != &rhs){
this->data = move(rhs.data);
return *this;
}
}
};
ostream& operator<<(ostream & s,const SimpleClass & rhs){
for (size_t i = 0; i != rhs.data.size(); ++i)
s << rhs.data[i];
return s;
}
int main()
{
SimpleClass one = {'o','n','e'};
SimpleClass two = {'t','w','o'};
{
SimpleClass & lValRef = one;
SimpleClass && rValRef = std::move(two);
}
cout << "one : " << one << endl;
cout << "two : " << two << endl;
{
SimpleClass temp(std::move(one));
SimpleClass tempAssignment;
tempAssignment = std::move(two);
}
cout << "one : " << one << endl;
cout << "two : " << two << endl;
return 0;
}
Aucun commentaire:
Enregistrer un commentaire