I'm reading on copy elision (and how it's supposed to be guaranteed in C++17) and this got me a bit confused (I'm not sure I know things I thought I knew before). So here's 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
}
The way I see it, cases A and B perform a direct construction on the return value so copy elision has no meaning here, while case C cannot perform copy elision because there are multiple return paths. Are these assumptions correct?
Also, I'd like to know if
- there's a better way of writing the above (e.g. have a
std::string retval;
and always return that one or write casesA
andB
asreturn string("1")
etc) - there's any move happening, for example
"1"
is a temporary but I'm assuming it's being used as a parameter for the constructor ofstd::string
- there are optimization concerns I ommited (e.g. I believe C could be written as
return{}
, would that be a better choice?)