3 ms·
C++ for C programmers, part 1/2 (the non-OO features)
- pavlov 17y agoThings that C programmers need to know about C++: - malloc() is broken. You need to cast the result. - Casting is broken. Even though C-style casting is available, you can't use it to reliably cast a void * as an object even when you know the type. - Pointers are broken. C++ introduces "references", a kind of non-nullable pointer which doesn't look like a pointer, makes a syntactic mess of what & means, and is used inconsistently wherever one could simply always use a pointer. - Exporting functions is broken. C++ functions can't be reliably exported as public APIs, unless you are absolutely sure your OS and compiler will never be updated. You must use #ifdefs to wrap the functions in 'extern "C"' declarations to have a stable plain-C API.
- gte910h 17y agoAs a person who's worked with C programmers trying to be C++ programmers a couple times, the following gave me a hearty laugh: > Pointers are broken. C++ introduces "references", a kind of non-nullable pointer which doesn't look like a pointer, makes a syntactic mess of what & means, and is used inconsistently wherever one could simply always use a pointer. I've heard argued "But but, its a Amp, it shouldn't mean that!"
- tbrownaw 17y ago- malloc() returns void* because it allocates memory, not objects. If you want your objects initialized, use 'new'. - I was under the impression that a round-trip through void* always worked? Or do you mean that "Derived d;Base * b = (Base* )(void* )&d;" doesn't work (which I wouldn't consider "broken")? - I like knowing that something won't be null. Also, your "bitwise and" operator was already an overloaded mess. - You only need the #ifdefs if you still have to interface with legacy C code that has variables named "class" or other such foolishness that makes it not compilable as C++. :)
- philwelch 17y agoThe C++ STL's map (the associative array) is idiosyncratic in one important respect: while most associative arrays, like Perl and Ruby hash tables, C# dictionaries, and Java HashMaps are hash tables with O(1) performance, the C++ map is in fact sorted by key, yielding O(log n) performance. Unless you need your keys sorted for whatever reason I wouldn't recommend the STL map.