C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Return Value Optimisation whenever you need it (guaranteed elision)

From: Federico Kircheis <federico_at_[hidden]>
Date: Mon, 17 Jul 2023 06:44:30 +0200
I would also like to be able to force NRVO

Here is an implementation that works with the big three compilers and
probably other:

https://godbolt.org/z/3drvsecKq

it does not require assembly and does not use platform-specific tricks.

And uses the same technique for having rvo before c++17:

  https://fekir.info/post/how-to-force-return-value-optimization/


Obviously it has the downsides not being able to put such objects in
std::list or other containers for non copyable and non moveable types,
but fortunately I never had such use-case


The main disadvantage is that in case of more complex functions, the
compiler might not apply NVRO, for example

----
struct s{
     explicit s(int);
     s(const s&);
     s& operator=(const s&);
     s(s&&) noexcept;
     s& operator=(s&&) noexcept;
     ~s();
};
s fun(int i){
     auto a = s(i);
     bar(a);
     return i ? a : a;
}
----
Counterintuitively, adding indirections helps to reduces the number of 
copies/moves
----
namespace{
s fun_0(int i){
     auto a = s(i);
     bar(a);
     return a;
}
s fun_1(int i){
     auto a = s(i+1);
     return a;
}
}
s fun(int i){
     if(i){
         return fun_0(i);
     } else {
         return fun_1(i);
     }
}
----
Again, tested with gcc/clang
msvc needs a little help
https://godbolt.org/z/qdvd1nxrf
I've listed here some observation about nvro
https://fekir.info/post/guaranteed-copy-elision/

Received on 2023-07-17 04:44:36