Prev: return value optimization vs. returning a boost::shared_ptr of container
Next: return value optimization vs. returning a boost::shared_ptr of container
From: Jeff Flinn on 15 Jun 2010 04:59 Goran wrote: > On Jun 15, 11:05 am, Peng Yu <pengyu...(a)gmail.com> wrote: >> Hi, >> >> I heard that most (if not all) containers in C++ standards (including >> the upcoming one) and in boost.org do not follow copy on write >> semantics. (Please correct me if I'm wrong.) >> >> Therefore, if I need to construct some container in a function and >> return it. I'd better return a shared_ptr of the container rather than >> the container itself. For example, should return >> boost::shared_ptr<tr1::unordered_map> rather than tr1::unordered_map. >> >> 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? > > I think so, too, but you have swap method, which is efficient. So: > > LibMapType map; > map.swap(LibFuncReturningMap(...)); IIRC, that won't compile on gcc 4.0.1 for me(but does with MSVC's extensions). I need to: > LibMapType map; > LibFuncReturningMap(...).swap(map); Jeff -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ] |