Yeah, c++ is optimized for every single bit and every single cpu cycle, right? But there are constellation in which you pay extra just because you can not express what should be done within the language itself. Here it goes:
Whenever you have a class with cheap copy semantics aka. smart classes like string, smart pointer or alike your might meet the following constellation:
shared_ptr myObject; if (some_condition) { myObject = f1(); } else { myObject = f2(); } // using myObject here
As myObject is used after the if branches it must be declared in advance. But at this point it can only be initialized with the default constructor as the right initialization information is not available until the if branches. Within the if branches operator= is then called with the right "initial" information for the object, as f1 and f2 each return a smart_ptr object. The previous initalization therefore was a waste of time.
Mini-ifs would solve the abover problem but are no general solution. Think about more than 2 possibilities or even a switch statement. A pointer to a shared_ptr is no solution, because this indirection breaks the reference counting of the smart object - the pointer is kept but the smart object itself is deleted, thus the reference counter doesn't reflect the actual use count. Allocating the shared_ptr on the heap is no solution either because in this case one doesn't need the smart class at all. References do not do the job either because they must be initialized from the beginning resulting in the problem that when the reference is introduced the initialization information is not avaiable yet.
You could argue that the first initialization does not really harm as not that much is done there. But the point is, why is everybody eager to tell you to use member initializations in constructors then, when default constructing is not expensive? It maybe isn't, but nevertheless one of the goals of C++ is to not waste CPU cycles.
My point here is: C++ has so many features and facets and still it is incomplete in some cases.
No comments:
Post a Comment