vendredi 29 mai 2020

C++ return value and move rule exceptions

When we return a value from a C++ function copy-initialisation happens. Eg:

std::string hello() {
    std::string x = "Hello world";
    return x; // copy-init
}

Assume that RVO is disabled.

As per copy-init rule if x is a non-POD class type, then the copy constructor should be called. However for C++11 onward, I see move-constrtuctor being called. I could not find or understand the rules regarding this https://en.cppreference.com/w/cpp/language/copy_initialization. So my first question is -

  1. What does the C++ standard say about move happening for copy-init when value is returned from function?

  2. As an extension to the above question, I would also like to know in what cases move does not happen. I came up with the following case where copy-constructor is called instead of move:

std::string hello2(std::string& param) {
    return param;
}

Finally, in some library code I saw that std::move was being explicitly used when returning (even if RVO or move should happen). Eg:

std::string hello3() {
    std::string x = "Hello world";
    return std::move(x);
}
  1. What is the advantage and disadvantage of explicitly using std::move when returning?

Aucun commentaire:

Enregistrer un commentaire