mercredi 6 juillet 2016

const reference to the member of the temporary object

It is well known feature of the C++ that const reference extends the life time of the temporary object, but is it acceptable to use constant reference to the member of the temporary object returned from the function?

Example:

#include <string>

std::pair<std::string, int> getPair(int n)
{
    return {std::to_string(n), n};
}

int main(int, char*[])
{
    const int x = 123456;
    const auto& str = getPair(x).first;
    printf("%d = %s\n", x, str.c_str());    
    return 0;
}

Output:

123456 = 123456

Aucun commentaire:

Enregistrer un commentaire