vendredi 18 mars 2022

assign from a const reference vs std::move()

Given the following snippet, what happens in each case (w.r.t. copying):


std::string GetString() {
 return "my string";
}

class MyObj {
...
std::string* mutable_str(); 
...
};

// 1) Assigning the value hold by reference 'a', makes a copy.
const std::string& a = GetString(); 
*Obj.mutable_str() = a

// 2) Not a copy, 'b' is a temporary. 
std::string b = GetString(); 
*Obj.mutable_str() = std::move(b);

Is my understanding correct?

Aucun commentaire:

Enregistrer un commentaire