samedi 25 décembre 2021

std::move Bug Spotted in C++ Primer 5th Edition

I looked at an example in C++ Primer explaining std::move. The example is as follows:

int &&rr1 = 42;
int &&rr3 = std::move(rr1);

In the explanation of the above code snippet, it is written that:

Calling move tells the compiler that we have an lvalue that we want to treat as if it were an rvalue. It is essential to realize that the call to move promises that we do not intend to use rr1 again except to assign to it or to destroy it. After a call to move, we cannot make any assumptions about the value of the moved-from object.

My first question is that: Can i now safely write std:: cout << rr1;? Since in the above quote paragraph, it is written that we cannot make any assumptions about the value of the moved-from object so is it guaranteed by the standard that std::cout << rr1; is safe(not UB or depends on implementation etc)?

Here is another example,

std::string str = "abc"; 
auto&& str2 = std::move(str); 
cout << str; // is this safe(not UB or depends on implementation)

Similarly, in the above snippet, is it safe to use the value of str like cout << str;?

If yes, then is this a mistake/bug in the book C++ Primer by Stanley.

Aucun commentaire:

Enregistrer un commentaire