On Tue, Aug 12, 2014 at 6:25 PM, L. David Baron <dba...@dbaron.org> wrote: > On Tuesday 2014-08-12 18:15 +0300, Aryeh Gregor wrote: >> 1) You can use the return value directly without assigning it to an>> 4) If >> the callee already holds a strong reference in a local variable, >> it can just return that reference instead of a raw pointer. This >> saves an addref/release if the caller puts the result in an nsCOMPtr. >> Currently you could do this by returning an already_AddRefed, but >> that's annoying because of (1) above, so people don't always do so. > > How does this save an addref/release? Is the compiler allowed to > use move constructors rather than copy constructors when > constructing the return value of a function from a local variable in > that function?
The compiler is required to use the move constructor (if one exists) instead of the copy constructor when constructing the return value of a function, and also when initializing an object from the return value of a function, or assigning the return value of a function. So if you have Foo GetFoo() { Foo f(1, 2, 7); /* do lots of stuff to f */ return f; } void MyFunction() { Foo f = GetFoo(); } the copy constructor of Foo will not get called anywhere. This is why with the patch, you can just return an nsCOMPtr without the forget() and it won't cause any extra addrefs. On Tue, Aug 12, 2014 at 6:29 PM, L. David Baron <dba...@dbaron.org> wrote: > This is done very commonly when we know some other data structure > (or the lifetime of |this|) owns the object, and will continue to > across the lifetime of the function. > > For example, if I open content/base/src/Element.cpp, I see this > pattern 5 times in the first 325 lines of the file. (Three > nsIDocument*, one nsIContent*, one nsIPresShell*.) If you know something else is holding a strong reference, why is it a problem to assign the result of a function that returns already_AddRefed<T> to a local variable of type T*? If the local variable's usage is otherwise legitimate, that assignment is perfectly safe and there's no reason for any compiler errors. _______________________________________________ dev-platform mailing list dev-platform@lists.mozilla.org https://lists.mozilla.org/listinfo/dev-platform