Re: C programmer migrating to C++
On Jan 25, 1:50 pm, 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.
One of big stumbling blocks for C people coming to C++ is
understanding the rule of three (http://en.wikipedia.org/wiki/
Rule_of_three_%28C%2B%2B_programming%29). Just sayin'...
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
relevant. I know this could be considered unsafe but imagine several
function calls inside of such function that also use NULL pointer. It
saves much work. In STL there are some values that represent bad or
boundary values such as string::npos or the one returned by iterator
end() method ( btw, it's irritating that every container has different
past-the-end element). Can I achieve something like default NULL
argument in C++ not using pointers but references?
In all honesty, that's where I'd use pointers with C++, too. Other
than that, perhaps you could get away nicely with "Null object"
pattern in some situations.
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; }
but I need do such things in my code:
string s;
foo(s);
I would like to do sth. like this:
string s = foo();
If I define foo function like that:
string foo(){ string buf="comp.lang.c++.moderated"; return buf; }
I'll work but as far as I understand it'll run several constructors
and copy constructors and I would like to make such operation work as
fast as [ string s("comp.lang.c++.moderated"); ]
You should not worry about that much (unless profiling shows that you
should). Compilers regularly do a trick called "return value
optimization" and elide as much code as possible during optimization.
(Yes, that means that what you see while debugging is not what happens
in optimized builds.)
BTW, is [ string s("comp.lang.c++.moderated"); ] faster than [ string
s ="comp.lang.c++.moderated"; ] or maybe it is compiler dependent?
That's the same. Compilers will actually use copy constructor in the
latter case.
Goran.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]