Re: C++ vs C
On Friday, July 18, 2014 2:53:30 PM UTC+2, JiiPee wrote:
so how do you do strings on C?
Is it:
struct String
{
int size;
char* data;
};
and then passing the string object to functions by pointer to do
operations? But even then both members are in risk of being modified by
accident somewhere in the code because they are not private members. I
mean its possible to change the size 15 and the data memory size is only
10. How do they avoid these problems in C?
I can actually point you back to the git project's strbuf struct and
its accompanying functions. From a C++ perspective, it's a mix
between std::string and std::vector<char>. In addition, it allows you
to release the owned memory just like std::unique_ptr<>::release does
and to initialize it with an already externally malloc'd block of
memory.
Apparently, string/buffer manipulation in C is enough of a hassle that
Linus felt the need to create an ABSTRACTION for this. Yes, an
ABSTRACTION. A word that possibly makes Linus think about classes
with virtual functions. ;) Anyhow, providing abstractions is what
good coders do. "Abstraction" does not imply big class hierarchies.
And just like you noticed, such an abstraction for strings and buffers
in C does not buy you as much as what you would get in C++. A C
programmer wold have to resist the temptation to manipulate a strbuf's
internals without going through one of the provided functions in the
strbuf interface. C++ has private for this. Also, a C programmer
using that strbuf abstraction has to pay close attention to the
interface's documentation which says things like "you MUST not do
this", "you HAVE to do this" in some areas IIRC -- including
initialization and deinitialization of such a struct. It's fairly
easy to forget "destruction" of a strbuf thus creating a memory leak.
In C++ that's done with the RAII pattern.
I really like the strbuf example. You could easily wrap this into a
C++11 class that is much nicer to deal with and less error-prone. I'm
saying C++11 because with C++11 we got move semantics. Move semantics
is needed in this case to safely cover all of what the strbuf
interface is offering you in C. I thought about writig a blog post
on that subject but eventually ditched the idea. It's not my job to
teach ignorant C programmers about what good C++ looks like and what
its benefits are.
Cheers!
sg