简体   繁体   中英

rvalue reference — I'm losing the value

I'm a bit confused about the rvalue reference so I have tried the following code:

std::vector<char> stringToChar(std::string& str)
{
    std::vector<char> rep(str.begin(), str.end());
    return rep;
}

std::vector<char>& cryptPassword(std::vector<char>&& password)
{
    // static const char _key = 56; //crypt password
    // for (char &c : password)
    //   c = c ^ _key;
    return (password);
}

std::vector<char>& stringToPassword(std::string& str)
{
    return cryptPassword(stringToChar(str));
}

In the first case I'm getting the correct output, but I the second case I'm getting garbage.

std::string str("Hello");
std::vector<char> tmp = cryptPassword(stringToChar(str));

//correct output
for (char c : tmp)
   std::cout << c;
std::cout << std::endl;

//garbage
tmp = stringToPassword(str);
for (char c : tmp)
   std::cout << c;
std::cout << std::endl;

The result of stringToChar(str) is an rvalue that will bind to the rvalue reference taken by cryptPassword() . When returning password the vector is copied and bound to the reference ( cryptPassword() returns an lvalue reference). The problem is that the return value is a temporary copy that has since died after the call to temp = stringToPassword() . Using it is Undefined Behavior.

Instead of returning a reference, return by value and std::move() password out:

std::vector<char> cryptPassword(std::vector<char>&& password)
{
    // ...  
    return std::move(password);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM