dimanche 25 mars 2018

Should I use std::move() on temporary (not automatic) objects as return value?

Is there any benefit over returning by rvalue-reference when the function itself returns by value?

std::string some_string() {
    std::stringstream ss("Hello World!");
    // same as return ss.str(); ?
    return std::move(ss.str());
}

Because as far as I know, the C++ compiler elides moves and copies completely for automatic objects using RVO. But what about temporary objects? Would it be even more performant to return by rvalue-reference like so?

std::string &&some_string() {
    std::stringstream ss("Hello World!");
    return ss.str();
}

I have read a few articles about rvalue-references and templates with rvalue parameters but return values still confuse me.

Aucun commentaire:

Enregistrer un commentaire