89 | | As with Java, unnecessary object creation is something you should avoid whenever possible. Just be smart about it when you code. For example, if a call to a method returns a new object and you call that method multiple times in the same context, then change your code to call this method only once and reuse the returned value. Another example: use private helper objects when it makes sense to avoid unnecessary object creation. |
| 89 | As with Java, unnecessary object creation is something you should avoid whenever possible. Just be smart about it when you code. |
| 90 | |
| 91 | * If a call to a method returns a new object and you call that method multiple times in the same context, then change your code to call this method only once and reuse the returned value. |
| 92 | * Use private helper objects when it makes sense to avoid unnecessary object creation. |
| 93 | |
| 94 | When you do need to create objects, check if it's possible to create them on the stack rather than on the heap. Consider the following example: |
| 95 | {{{ |
| 96 | #!cpp |
| 97 | Ptr<MgFoo> spFoo = new MgFoo(arg); |
| 98 | Bar(spFoo); |
| 99 | }}} |
| 100 | |
| 101 | In this case !MgFoo is a ref-counted object, and because of this you might think your only choice is call to new and assign the result to a smart pointer. In fact, if the call to Bar does not add any references to the object then the following code which doesn't call new also works: |
| 102 | {{{ |
| 103 | #!cpp |
| 104 | MgFoo foo(arg); |
| 105 | Bar(&foo); |
| 106 | }}} |
| 107 | |
| 108 | Of course the same stack vs. heap thinking applies to non-ref-counted objects. |