Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to check if RVO was applied?

Tags:

c++11

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?

like image 769
user81993 Avatar asked Mar 02 '16 00:03

user81993


1 Answers

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 
like image 98
PSkocik Avatar answered Sep 22 '22 11:09

PSkocik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!