Re: C programmer migrating to C++
On 25 Jan, 12:50, Bartosz Wiklak <bwik...@gmail.com> wrote:
Hello, I'm coding in C form many years but for a year or something
like that I'm trying to get rig of "bad" old habits and start to do
things better.
There are couple of annoyances in C++ I cannot solve - probably I'm
doing something wrong.
I wonder If someone could help me:
1)
Consider such function definition
void f( int k, const T* t, T2* t2=NULL);
In C I used pointers extensively. When I didn't want to overload
function's definition I used function's default NULL arguments to
indicate that this argument (and part of function's job) is not>
function overloads are clearer and more flexible than default argument
values and allow references.
For example you can just have
void f( int k, const T& t, T2& t2);
void f( int k, const T& t);
And you can even implement them both internally in with a private
method with the original signature -
In this way you can constrain the caller to the interface that you
want (no need to check for null pointers) AND the default T2 will be a
run time rather than
compile time constant (sometimes useful for replacement libraries)
2)
Returning objects:
Suppose I want to have a method that returns a "large" object, let it
be a "comp.lang.c++.moderated" string.
I can do it this way:
string& foo( string& buf ){ buf="comp.lang.c++.moderated"; return
buf; }
The new standard rvalue references will enable efficient return by
value for strings (and your own types if you write the appropriate
methods) so just write it as
string foo() { return "...."; }
string x = foo();
and any compiler supporting rvalue references will do just one
allocation and copy.
This is nothing to do with the current std return value optimisation
which is optional. This is mandatory with rvalue references and
appropriate STL.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]