What happens in this return statement?

I read about copying elision (and how it should be guaranteed in C ++ 17), and it confused me a bit (I'm not sure I know the things that I thought I knew before). So here is a minimal test case:

std::string nameof(int param)
{
    switch (param)
    {
    case 1: 
        return "1"; // A
    case 2: 
        return "2" // B
    }
    return std::string(); // C
}

As I can see, cases A and B perform a direct construction on the return value, so the elision copy does not make sense here, while C cannot copy because there are several return paths. Are these assumptions correct ?

In addition, I would like to know if

  • there is a better way to write above (for example, to have std::string retval;and always return this one or write cases Aand Bhow return string("1")and so on)
  • , "1" , , std::string
  • , (, , C return{}, ?)
+6
2

NRVO-, . , .

, , , . std::string , , .

, return std::string() return {} .

. , "1" . . .

, : ++ 17 copy elision . ,

std::string x = "X";

std::string x copy ( move).

+3

. :

std::string j = nameof(whatever);

:

  • std::string, j. ( .)

  • std::string, j, . ( .)

+1

Source: https://habr.com/ru/post/1014201/


All Articles