Here are three reminders about copy elision:
- Copy elision doesn’t happen if your constructor is using a universal reference
If you write a class such as this, there will be no copy elision:
template <typenameT>
class Foo
{
Foo(T&& other)
{}
}
This is because functions with universal references are not considered to be copy/move constructors by the compiler.
- Before C++17, different compilers might act in different ways regarding copy elision.
Copy elision was optional, and implementation-specific for most compilers before C++17. The picture is more varied the further back in time you go, so it’s not reliable.
- Distinguish between RVO and NRVO.
RVO (return value optimisation) happens when you return a temporary, and is mandatory since C++17:
Foo bar()
{
return Foo(); //no copying happens for sure
}
NRVO (named return value optimisation) is not mandatory but very often happens:
Foo bar()
{
Foo f;
return f; //no copying happens some of the time
}
Leave a Reply