Prev: return value optimization vs. returning a boost::shared_ptr of container
Next: shared_ptr question
From: Martin B. on 15 Jun 2010 22:56 Mathias Gaunard wrote: > On 15 juin, 10:05, Peng Yu <pengyu...(a)gmail.com> wrote: > >> If there is return value optimization (RVO), I think that I can return >> tr1::unordered_map as the compile can optimize away unnecessary coping >> in certain cases. But I think that there cases where RVO doesn't help. >> For example, if tr1::unordered_map is returned from a function that is >> only available in the object format (through linkage), the copying can >> not be avoided, right? > > RVO, if implemented, is consistent. NRVO should also be consistent if > all exit paths from the function return the same named object. > You should expect any compiler of good quality to implement NRVO, and > any decent compiler to implement RVO. > > Therefore you should return by value if that's what semantically makes > sense. There is no useless copy (or even move) going on when returning > a local variable by value (assuming the return type is the same of the > type of the return expression). > Except of course if someone wrote: container_t fn() { ... } ... container_t obj; obj = fn(); In this case (N)RVO cannot work and you always have to copy(move). br, Martin -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ]
From: Martin B. on 18 Jun 2010 00:30 Mathias Gaunard wrote: > On 16 juin, 14:56, "Martin B." <0xCDCDC...(a)gmx.at> wrote: > >> Except of course if someone wrote: >> container_t fn() { ... } >> ... >> container_t obj; >> obj = fn(); >> In this case (N)RVO cannot work and you always have to copy(move). > > NRVO or RVO remove useless copies, not assignments. Well, for me in day-to-day language, an assignment *is* a copy. > That's a different thing altogether and that simply cannot be done > because: > 1) this is not allowed by the language > 2) this doesn't work when fn may throw. > True. That's why I pointed out that return-by-value may be more expensive that other alternatives when doing an assignment instead of initialization. (I do think it does not really matter with C++0x move semantics, because this is also applied when assigning?) br, Martin -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ]
|
Pages: 1 Prev: return value optimization vs. returning a boost::shared_ptr of container Next: shared_ptr question |