Whether the r-value is used when creating the reference variable with std :: move (). [C ++]

Can someone help correct my understanding std::move?

I thought that if a reference to an r-value is out of scope, then it is referenced if it was assigned using an operator std::move. Why is this not the case in the code below?

#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 play with him here .

I always thought that using std::moveis a way to leave objects in a “deleted state”. Therefore, I was surprised that the "two" printed something for the first time. Is it used to create && r-value, as I did ('rValRef')? [I understand that a std::move()will be required around my "rValRef" for it to work as desired].

, , . , , :) .

#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;
}
+4
1

, .

string && rValRef = std::move(two);
string newS(rValRef);

rValRef rvalue std::string, rValRef lvalue. , -, , , lvalue. rValRef - , , lvalue.

, std::move, ( , std::move xvalue, rvalue):

string newS(std::move(rValRef)); 
+5

All Articles