From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: (qmail 5682 invoked by alias); 19 Dec 2013 08:31:56 -0000 Mailing-List: contact gcc-help-help@gcc.gnu.org; run by ezmlm Precedence: bulk List-Id: List-Archive: List-Post: List-Help: Sender: gcc-help-owner@gcc.gnu.org Received: (qmail 5672 invoked by uid 89); 19 Dec 2013 08:31:55 -0000 Authentication-Results: sourceware.org; auth=none X-Virus-Found: No X-Spam-SWARE-Status: No, score=-2.5 required=5.0 tests=AWL,BAYES_00,FREEMAIL_FROM,RCVD_IN_DNSWL_LOW,SPF_PASS autolearn=ham version=3.3.2 X-HELO: mail-la0-f51.google.com Received: from mail-la0-f51.google.com (HELO mail-la0-f51.google.com) (209.85.215.51) by sourceware.org (qpsmtpd/0.93/v0.84-503-g423c35a) with (AES128-SHA encrypted) ESMTPS; Thu, 19 Dec 2013 08:31:24 +0000 Received: by mail-la0-f51.google.com with SMTP id ec20so303994lab.38 for ; Thu, 19 Dec 2013 00:31:21 -0800 (PST) X-Received: by 10.152.7.67 with SMTP id h3mr61429laa.29.1387441881175; Thu, 19 Dec 2013 00:31:21 -0800 (PST) Received: from [130.233.179.5] ([130.233.179.5]) by mx.google.com with ESMTPSA id bl6sm1850768lbb.5.2013.12.19.00.31.19 for (version=TLSv1 cipher=ECDHE-RSA-RC4-SHA bits=128/128); Thu, 19 Dec 2013 00:31:20 -0800 (PST) Message-ID: <52B2AED7.9090203@gmail.com> Date: Thu, 19 Dec 2013 08:31:00 -0000 From: =?ISO-8859-1?Q?Henrik_Mannerstr=F6m?= User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:24.0) Gecko/20100101 Thunderbird/24.2.0 MIME-Version: 1.0 To: gcc-help@gcc.gnu.org Subject: RVO (let the compiler copy) Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit X-IsSubscribed: yes X-SW-Source: 2013-12/txt/msg00132.txt.bz2 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 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; }