peter koch wrote:
> mlimber skrev:
> > peter koch wrote:
> > > mlimber skrev:
> > > > If you're lucky, the compiler might optimize the copy of the list away,
> > > > but generally speaking it can't do so. A better way would be to pass
> > > > the list in as a reference:
> > > >
> > > > void ball::split( GLint ntimes, list<ball*>& new_balls )
> > > > {
> > > > list.clear();
> > > > // ... same stuff as before, except for the return
> > > > }
> > > >
> > >
> > > I have two questions: first why you choose to force a weird syntax
> > > because some optimization not would take place. Is there any indication
> > > that the procedure in question is on an expensive path?
> >
> > It could be premature optimization, sure. But let's also not
> > prematurely pessimize.
>
> It is NEVER premature pessimization if the result requires you to write
> obfuscated code such as
> container <t> c;
> cfunc(c);
> instead of
> container <t> c = cfunc();
>
> > First, the OP didn't specify the compiler in question. Some don't do
> > the RVO at all. Second, RVO can only be applied on initialization. For
> > instance...
>
> Just out of curiosity. What compiler released in this millenium does
> not do RVO or NRVO?
Well, like I said, the OP didn't specify, and unfortunately, not
everyone has the option of use modern compilers. (Half of my current
project uses VC6, for instance, while the other half uses a quite
compliant EDG-based compiler, and some code has to work on both).
> >
> > vector<int> Foo()
> > {
> > vector<int> v;
> > v.push_back( 1 );
> > v.push_back( 2 );
> > return v;
> > }
> >
> > void Bar()
> > {
> > vector<int> v = Foo(); // RVO applied!
> > // ... use v somehow ...
> > v = Foo(); // RVO not applied!
> > }
>
> Right - but the first solution is still preferable. First, you keep the
> natural look of the code (which is most important - code is written to
> be read!). Second, you can more easily get the strong exception
> guarantee here and lastly this code will be as efficient as your
> "return value in a parameter" as soon as the new r-value extensions get
> implemented
Certainly this is the preferable syntax, but it, too, has a drawback
besides the question of compiler support: it requires the programmer to
remember to make use of RVO and not perform an implicit copy. I see it
as a trade-off, which can be decided one way or the other in specific
instances by the needs of the project, but if a conservative approach
should be taken, then the explicit parameter approach should be used.
Cheers! --M