RVO (let the compiler copy)

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



This question came up on SO (
http://stackoverflow.com/questions/7320520/optimizing-the-number-of-constructor-calls)
and I was baffled since it went against the mantra "let the compiler do
the copying". Do you have an idea of what is going on? Why is the
commented version of operator+ worse? I compile with g++ -std=gnu++11
-Wall -Wextra -pedantic -O2  mwe.cc

BR,
Henrik

#include <iostream>

struct Imaginary {
  Imaginary(int a_, int b_) : a(a_), b(b_) {
    std::cout << "int/int ctor" << std::endl;
  };
 
  Imaginary(Imaginary const & orig) {
    a = orig.a;
    b = orig.b;
    std::cout << "Copy ctor (" << a << ',' << b << ')' << std::endl;
  }

  Imaginary & append(Imaginary const & rhs) {
    a = 10 * a + rhs.a;
    b = 10 * b + rhs.b;
    return *this;
  }

  int a;
  int b;
};

/* This calls the copy constructor once */
Imaginary operator+(Imaginary const & lhs, Imaginary const & rhs) {
  Imaginary tmp(lhs);
  tmp.append(rhs);
  return tmp;
}

/* This calls the copy constructor twice
Imaginary operator+(Imaginary lhs, Imaginary const & rhs) {
  lhs.append(rhs);
  return lhs;
}
*/

int main()
{
    Imaginary x(1, 1);
    Imaginary y(2, 1);

    Imaginary c = x + y;
    return c.a;
}





[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux