I had this whole story about my frustrating journey to finding out that an unordered map I was returning from a function was not in fact RVO'd even though I was certain it was at an earlier time that it was but irrelevant.
Is there a way to check if RVO is happening in any given function? Or like a list of do's and dont's to follow to get the outcome I desire?
Yes. Create hooks for the lifecycle methods of your class:
#include <iostream>
struct A{
A()
{ std::cout<<"Ctor\n"; }
A(const A& o)
{ std::cout<<"CCtor\n"; }
A(A&& o)
{ std::cout<<"MCtor\n"; }
~A()
{ std::cout<<"Dtor\n"; }
private:
int vl_;
};
A getA(){
A a;
return a;
}
int main(){
A b = getA();
return 0;
}
Now with RVO, b is the same object as a
in getA
so you'll only see
Ctor
Dtor
You can suppress RVO, e.g., by adding an additional return point:
return a;
return A{a};
or moving:
return std::move(a);
And then you'll see:
Ctor
Mctor
Dtor
Dtor
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With