For example lets take the instance of passing a CString object, [a string wrapper for MFC].
so if we call void Foo(CString bar) when we could have used void Foo(const CString& bar) what's the difference you might ask? Well a couple of things, when passing a new instance of a variable, you now have to add a runtime allocation and deallocation of the memory used by the new local object. Also the memory of the source object must be copied over. You may also be introducing a call to a copy constructor which could cause even more repeated work.
What I consider even worst is defining a function with a non-const pointer which should be const. Who knows what the function may or may not do to your pointer but also, you may end up breaking other designs by forcing the passing of an unprotected buffer. One of the best examples I see of this is when char* is passed instead of const char*. If you have any smart objects like a CString they will automatically cast to const char but will force the user to make explicit calls to return an unprotected buffer, which in turns should make the user think twice [which is a pretty good design move in my opinion]
In Summary:
Always start with const& and const* for your input variables and only use something different when needed.
No comments:
Post a Comment