[HH] c++ strings?

Matthew Gillen me at mattgillen.net
Tue Nov 20 10:06:01 EST 2012


On 11/20/2012 09:37 AM, Mark Woodward wrote:
> This is a pet peeve of mine. What is a C++ "purist?" C++ is a very broad
> language with a lot of capabilities. The "cout" object is merely one of
> those to be used or not based on need.

"Need" is often confused with preference, where preferences don't often 
account for the reasoning behind conventions.

> For some reason, "purists" want to ignore that C++ is for all practical
> purposes a set of extensions to C. Furthermore, that, for some reason,
> programs must be coded entirely differently than you would C code. I
> reject this mentality as something akin to "java-envy" or something.
>
> There is nothing wrong with the various incarnations of printf. There is
> no reason not to use malloc if you want. There is no reason not to use
> "char *" for strings. Templates need not be used.
>
> C++ code is that which compiles using a C++ compiler, not some
> ideological construct that must be adhered too.

Except that if you mix C-style input/output and C++-style input/output, 
bad things can happen.  If you mix C-style malloc with C++-style "new", 
bad things can happen.  The compiler generally assumes you know what 
you're doing if you mix C and C++ idioms, and so it won't protect you 
from shooting yourself in the foot.

So strictly speaking, you're right, there's nothing wrong with using 
printf in a C++ program.  But you better either not use any C++ 
cout-style statements on that same stream, or you better know what 
you're doing (e.g. did you make all the calls to sync_with_stdio() in 
the right place?  What, didn't know about that function?  Good luck with 
portability...).

Likewise with malloc vs. new: they are NOT freely interchangeable. 
Managing a C++ class with 'new/delete' will ensure that 
constructors/destructors get called.  Managing that same object with 
malloc/free does not invoke constructor/destructor pairs, it merely 
allocates memory.  Furthermore, there is no guarantee that the way 'new' 
and 'malloc' manage memory is compatible; e.g. you could have issues if 
you 'new' and object and then 'free' it, or 'malloc' and object then 
'delete' it.

So instead of chasing noob programmers around and beating them over the 
head with all these subtle bugs that only manifest themselves on certain 
systems, it's a lot easier to just make the rule: stick with one set of 
idioms.

Matt



More information about the Hardwarehacking mailing list