Topic: May be copy ctor called when returning class instance?


Author: Alberto Ganesh Barbati <AlbertoBarbati@libero.it>
Date: Sat, 22 Sep 2007 20:08:18 CST
Raw View
James Dennett ha scritto:
> Ondra Holub wrote:
>>
>> A fn()
>> {
>>     return A(ctor parameters);
>> }
>>
>> Is it ensured by standard, that copy constructor of A is not called or
>> is it only common optimization?
>
> It is not guaranteed, though the standard does permit an
> implementation to elide the copy in this case (and it is
> indeed a common, maybe even now universal, optimization).
>

Moreover, even in the case the copy is elided, the copy constructor
must be accessible. The copy still occurs semantically although the copy
constructor may not be actually called.

Ganesh

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html                      ]





Author: ron@spamcop.net (Ron Natalie)
Date: Sun, 23 Sep 2007 01:08:13 GMT
Raw View
James Dennett wrote:

>> Is it ensured by standard, that copy constructor of A is not called or
>> is it only common optimization?
>
> It is not guaranteed, though the standard does permit an
> implementation to elide the copy in this case (and it is
> indeed a common, maybe even now universal, optimization).
>

Note that even when elided, the copy constructor must be accessible
as if it were going to be used.

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html                      ]





Author: jdennett@acm.org (James Dennett)
Date: Sat, 22 Sep 2007 06:11:20 GMT
Raw View
Ondra Holub wrote:
> Hello all.
>
> when I have some class
>
> class A
> {
> // Some stuff
> };
>
> And I need to return instance of this class (not reference, nor
> pointer) from some function
>
> A fn()
> {
>     return A(ctor parameters);
> }
>
> Is it ensured by standard, that copy constructor of A is not called or
> is it only common optimization?

It is not guaranteed, though the standard does permit an
implementation to elide the copy in this case (and it is
indeed a common, maybe even now universal, optimization).

-- James

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html                      ]