Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for C++ copy ellision

I ran across this article on copy ellision in C++ and I've seen comments about it in the boost library. This is appealing, as I prefer my functions to look like

verylargereturntype DoSomething(...)

rather than

void DoSomething(..., verylargereturntype& retval)

So, I have two questions about this

  1. Google has virtually no documentation on this at all, how real is this?
  2. How can I check that this optimization is actually occuring? I assume it involves looking at the assembly, but lets just say that isn't my strong suit. If anyone can give a very basic example as to what successful ellision looks like, that would be very useful

I won't be using copy ellision just to prettify things, but if I can be guaranteed that it works, it sounds pretty useful.

like image 673
Steve Avatar asked Nov 29 '22 19:11

Steve


2 Answers

I think this is a very commonly applied optimization because:

  1. it's not difficult for the compiler to do
  2. it can be a huge gain
  3. it's an area of C++ that was a commonly critiqued before the optimization became common

If you're just curious, put a debug printf() in your copy constructor:

class foo {
public:
    foo(): x(0) {};

    foo(int x_) : x( x_) {};

    foo( foo const& other) : x( other.x) {
        printf( "copied a foo\n");
    };

    static foo foobar() {
        foo tmp( 2);

        return tmp;
    }


private:
    int x;
};



int main()
{
    foo myFoo;

    myFoo = foo::foobar();

    return 0;
}

Prints out "copied a foo" when I run an unoptimmized build, but nothing when I build optimized.

like image 98
Michael Burr Avatar answered Dec 11 '22 00:12

Michael Burr


From your cited article:

Although copy elision is never required by the standard, recent versions of every compiler I’ve tested do perform these optimizations today. But even if you don’t feel comfortable returning heavyweight objects by value, copy elision should still change the way you write code.

It is better known as Return Value Optimization.

like image 32
msw Avatar answered Dec 10 '22 22:12

msw