Criticism of C++
C++ is a general-purpose programming language with imperative, object-oriented and generic programming features. Many criticisms have been leveled at the programming language from, among others, prominent software developers like Linus Torvalds,[1] Richard Stallman,[2] and Ken Thompson.[3]
C++ is a multiparadigm programming language[4] with backward compatibility with the programming language C.[5] This article focuses not on C features like pointer arithmetic, operator precedence or preprocessor macros, but on pure C++ features that are confusing, inefficient or dangerous for normal users of the language.
Slow compile times
The natural interface between source files in C/C++ are header files. Each time a header file is modified, all source files that are including the header file should recompile their code, and the processing of header files performed by the compiler incurs various compilation speed penalties.[6] C only has limited amounts of information like typedefs, constants/macros, struct declarations and function prototypes in header files. C++ stores its classes in header files and they are not only exposing their public variables and public functions like C with its structs and function prototypes, but also their private functions. This forces a recompile of all source files that are including the header file, even when these private functions only are limited to their own source file. This problem is magnified where the classes are written as templates, forcing all of their code into the non cacheable header files. Large C++ projects can therefore be extremely slow to compile.[7]
One present solution for this is to use the Pimpl idiom. This makes all the object sizes equal on stack, only containing a pointer to the implementation object on the heap. This of course comes with the cost of a unnecessary heap allocation for each object.
Another method is to use precompiled headers for header files that are fairly static.
One suggested solution is to use a module system.[8]
Global format state of <iostream>
C++ <iostream> unlike C <stdio.h> relies on a global format state. This fits very poorly together with exceptions, when a function must interrupt the control flow, after an error, but before resetting the global format state. One fix for this is to use Resource Acquisition Is Initialization (RAII) which is implemented in Boost[9] but is not a part of the C++ Standard Library.
The global state of <iostream> uses static constructors which causes overhead.[10] Another source of bad performance is the use of std::endl instead of '\n' when doing output, because of it calling flush as a side effect.[11] C++ <iostream> is by default synchronized with <stdio.h> which can cause performance problems. Shutting it off can improve performance but forces giving up thread safety.[12]
Here follows an example where an exception interrupts the function before std::cout can be restored from hexadecimal to decimal. The error number in the catch statement will be written out in hexadecimal which probably isn't what one wants:
#include <iostream>
#include <vector>
int main() {
try {
std::cout << std::hex;
std::cout << 0xFFFFFFFF << std::endl;
std::vector<int> vector(0xFFFFFFFFFFFFFFFFL,0); // Exception
std::cout << std::dec; // Never reached
} catch(std::exception &e) {
std::cout << "Error number: " << 10 << std::endl; // Not in decimal
}
return(EXIT_SUCCESS);
}
It is acknowledged[13][14] even by C++ standards body that the iostreams interface is an aging interface that needs to be replaced eventually. This design forces the library implementers to adopt solutions that impact performance greatly.[15]
Heap allocations in containers
After the inclusion of the STL in C++, its templated containers were promoted while the traditional C arrays were strongly discouraged.[16] One important feature of containers like std::string and std::vector is them having their memory on the heap instead of on the stack like C arrays.[17][18] To stop them from allocating on the heap, one would be forced to write a custom allocator, which isn't standard. Heap allocation is slower than stack allocation which makes claims about the classical C++ containers being "just as fast" as C arrays somewhat untrue.[19][20] They are just as fast to use, but not to construct. One way to solve this problem was to introduce stack allocated containers like boost::array[21] or std::array.[22] Here is an example where the heap allocations are written out just for the trivial task of initializing a vector. Using a C array wouldn't trigger any heap allocations at all, which shows the cost of some of these high level abstractions:[23]
#include <iostream>
#include <vector>
void* operator new(size_t size) {
std::cout << "Heap allocation" << std::endl;
return(malloc(size));
}
int main() {
// Will probably allocate on heap 5 times
// We "could" reserve memory in the constructor,
// but let's forget it!
std::vector<int> vector;
for(auto i=0; i<10; ++i)
vector.push_back(i);
for(auto &i : vector)
std::cout << i << std::endl;
return(EXIT_SUCCESS);
}
Iterators
The philosophy of the Standard Template Library (STL) embedded in the C++ Standard Library is to use generic algorithms in the form of templates using iterators. These iterators often deal with heap allocated data in the C++ containers and becomes invalid if the data is independently moved by the containers. Functions that change the size of the container often invalidate all iterators pointing to it, creating dangerous cases of undefined behavior. The complex categories of iterators have also been criticized.[24][25] Here is an example where the iterators in the for loop get invalidated because of the std::string container changing its size on the heap:
#include <iostream>
#include <string>
int main() {
std::string text = "One\nTwo\nThree\nFour\n";
// Let's add an '!' where we find newlines
for(auto i = text.begin(); i != text.end(); ++i) {
if(*i == '\n') {
// i =
text.insert(i,'!')+1;
// Without updating the iterator this program has
// undefined behavior and will likely crash
}
}
std::cout << text;
return(EXIT_SUCCESS);
}
Auto and deduced type systems
Introduced with the C++11 standard, the auto feature and keyword defined a way to declare variables without writing down exactly its specific type as prior C++ standards required. The necessity for an auto feature might be seen as a result of the strong influence of the Intuitionistic Type Theory introduced by Per Martin-Löf in the 70s. As mathematics and computer science became more closely related, and perhaps to the detriment of the original relationship of C++ with its roots in computer engineering, it was unsurprising that functional programming dominated the development of the language from 90s on, with marked influences from dependently typed languages like Agda.
However the introduction of a context-dependent type system into a language that is used in mission critical systems like x-ray machines, internet routers, avionics, gaming systems among others introduces an uncertainty that can be fatal. The first two chapters (40 pages) of what can be considered the bible of modern C++, Effective Modern C++ by Scott Meyers,[26] deals with unraveling the extremely complex set of rules that govern type deduction by templates and auto.
The complexity introduced by auto is so harmful as to entice LLVM to write in its Coding Standards[27] to use auto if and only if it makes the code more readable or easier to maintain, thus discouraging the policy of “almost always auto". LLVM also warns[28] for that the default behavior of auto is copy, which can be particularly expensive in range-based for loops.
Uniform initialization syntax
The C++11 uniform initialization syntax and std::initializer_list share the same syntax which are triggered differently depending on the internal workings of the classes. If there is a std::initializer_list constructor then this is called. Otherwise the normal constructors are called with the uniform initialization syntax. This can be confusing for beginners and experts alike[29][30]
#include <iostream>
#include <vector>
int main() {
int integer1{10}; // int
int integer2(10); // int
std::vector<int> vector1{10,0}; // std::initializer_list
std::vector<int> vector2(10,0); // size_t,int
std::cout << "Will print 10"
<< std::endl << integer1 << std::endl;
std::cout << "Will print 10"
<< std::endl << integer2 << std::endl;
std::cout << "Will print 10,0," << std::endl;
for(auto &i : vector1) std::cout << i << ',';
std::cout << std::endl;
std::cout << "Will print 0,0,0,0,0,0,0,0,0,0," << std::endl;
for(auto &i : vector2) std::cout << i << ',';
return(EXIT_SUCCESS);
}
Exceptions
One problem with C++ exceptions is that they shouldn't be allowed to leave destructors, which impedes the RAII idiom. RAII advises acquiring resources in the constructor, and releasing them in the destructor. Exceptions often result in stack unrolling which calls more destructors. If two exceptions leave their destructors in parallel the C++ runtime will call std::terminate() which exits the program.[31] This forces one to use global variables or other tricks to report errors from destructors.
Another concern is that the zero-overhead principle[32] isn't compatible with exceptions[33]
Here is an example where exceptions are allowed to leave destructors and therefore provoke a std::terminate():
#include <iostream>
#include <stdexcept>
class connection {
public:
connection() = default;
~connection() noexcept(false) {
throw std::runtime_error("Connection Error!");
}
};
static void InitConnection() {
connection connection1;
connection connection2;
// This second object will lead to std::terminate() because of
// the stack unrolling triggering two exceptions in parallel.
}
int main() {
try {
InitConnection();
} catch(std::runtime_error &e) {
std::cout << e.what() << std::endl;
}
return(EXIT_SUCCESS);
}
Strings without Unicode
The C++ Standard Library offers no real support for Unicode compared to frameworks like Qt.[34][35] std::basic_string::length will only return the underlying array length which is acceptable when using ASCII or UTF-32 but not when using variable length encodings like UTF-8 or UTF-16. In these encodings the array length has little to do with the string length in code points.[36] There are no support for advanced Unicode concepts like normalization, surrogate pairs, bidi or conversion between encodings. There isn't even a way to change between lowercase and uppercase letters without resorting to the C standard library.[37]
This will print out the length of two strings with the equal amount of Unicode code points:
#include <iostream>
#include <string>
#include <cassert>
int main() {
// This will print "22 18",
// UTF-8 prefix just to be explicit
std::string utf8 = u8"Vår gård på Öland!";
std::string ascii = u8"Var gard pa Oland!";
std::cout << utf8.length() << " " << ascii.length() << std::endl;
assert(utf8.length() == ascii.length()); // Fail!
return(EXIT_SUCCESS);
}
Important C99 features missing
There are several important features from C99 missing in C++. This makes it harder and sometimes impossible to use C++ compilers with newer C code. This criticism must still be regarded to be somewhat milder because of C++ being a different language than C. It is only mentioned here because of these features creating big problems when using modern C code in C++ projects.
Designated Initializers
With designated initializers, arrays can be initialized more flexibly at compile time. In C++ one would instead use constexpr functions to do it.
#include <stdio.h>
#include <stdlib.h>
enum
{
WELCOME,
STATEMENT = 3,
COMMENT = 6,
GOODBYE = 11,
MAX,
};
const char *Text[MAX] =
{
[WELCOME] = "Welcome fellow programmer!",
[STATEMENT] = "Here we are using designated initializers",
[COMMENT] = "They are not a part of the C++ standard",
[GOODBYE] = "See you later!"
};
int main()
{
for(size_t i=0; i<MAX; i++)
{
if(!Text[i]) puts("Waiting");
else puts(Text[i]);
}
return(EXIT_SUCCESS);
}
Variable Length Arrays
In this example we are using Variable Length Array to allocate dynamic memory on the stack. This can replace heap allocations with faster stack allocations for dynamic memory. Several C++ compilers are supporting this feature independently of the C++ standard.[38] There is no similar feature in C++ where one is forced to use the heap for dynamic memory allocation.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void Fibonacci(size_t size)
{
// Here we are using a Variable Length Array.
// We can use the stack for dynamic allocation.
if(size < 2) return;
unsigned long long array[size];
memset(array,0,sizeof(array));
array[0] = 0;
array[1] = 1;
for(size_t i=2; i<size; i++)
{
array[i] = array[i-1] + array[i-2];
if(array[i] < array[i-1])
{
array[i] = 0;
break;
}
}
for(size_t i=0; i<size; i++)
printf("%llu ", array[i]);
}
int main()
{
Fibonacci(100);
return(EXIT_SUCCESS);
}
Restrict keyword
For very time critical tasks restrict pointers can help the compiler optimize the code by avoiding pointer aliasing. Without this keyword one might be required to use inline assembler to achieve the same performance in C++.
See also
References
- ↑ "Re: [RFC] Convert builin-mailinfo.c to use The Better String Library" (Mailing list). 6 September 2007. Retrieved 31 March 2015.
- ↑ "Re: Efforts to attract more users?" (Mailing list). 12 July 2010. Retrieved 31 March 2015.
- ↑ Andrew Binstock (18 May 2011). "Dr. Dobb's: Interview with Ken Thompson". Retrieved 7 February 2014.
- ↑ "What is "multiparadigm programming"?".
- ↑ "Are there any features you'd like to remove from C++?".
- ↑ Walter Bright. "C++ compilation speed".
- ↑ "Less is exponentially more".
Back around September 2007, I was doing some minor but central work on an enormous Google C++ program, one you've all interacted with, and my compilations were taking about 45 minutes on our huge distributed compile cluster.
- ↑ "A Module System for C++" (PDF).
- ↑ "iostream state saver".
- ↑ "#include <iostream> is Forbidden".
- ↑ "std::endl".
Use of std::endl in place of '\n', encouraged by some sources, may significantly degrade output performance. In many implementations, standard output is line-buffered, and writing '\n' causes a flush anyway, unless std::cout.sync_with_stdio(false) was executed. In those situations, unnecessary endl only degrades the performance of file output, not standard output.
- ↑ "Sync with stdio".
- ↑ "Is C++'s IOStream a bad design? - Quora". www.quora.com. Retrieved 2016-05-03.
- ↑ "N4412: Shortcomings of iostreams". open-std.org. Retrieved 2016-05-03.
- ↑ "HFTrader/MyPasteBin". GitHub. Retrieved 2016-05-03.
- ↑ "A Conversation with Bjarne Stroustrup".
- ↑ "std::vector".
- ↑ "std::string".
- ↑ "A Conversation with Bjarne Stroustrup".
I think a better way of approaching C++ is to use some of the standard library facilities. For example, use a vector rather than an array. A vector knows its size. An array does not... Most of these techniques are criticized unfairly for being inefficient. The assumption is that if it is elegant, if it is higher level, it must be slow. It could be slow in a few cases, so deal with those few cases at the lower level, but start at a higher level. In some cases, you simply don't have the overhead. For example, vectors really are as fast as arrays.
- ↑ Bjarne Stroustrup. "Why are the standard containers so slow?".
People sometimes worry about the cost of std::vector growing incrementally. I used to worry about that and used reserve() to optimize the growth. After measuring my code and repeatedly having trouble finding the performance benefits of reserve() in real programs, I stopped using it except where it is needed to avoid iterator invalidation (a rare case in my code). Again: measure before you optimize.
- ↑ "boost::array".
As replacement for ordinary arrays, the STL provides class std::vector. However, std::vector<> provides the semantics of dynamic arrays. Thus, it manages data to be able to change the number of elements. This results in some overhead in case only arrays with static size are needed.
- ↑ "std::array".
The struct combines the performance and accessibility of a C-style array with the benefits of a standard container, such as knowing its own size, supporting assignment, random access iterators, etc.
- ↑ Linus Torvalds. "Re: [RFC] Convert builin-mailinfo.c to use The Better String Library.".
You can write bad code in any language. However, some languages, and especially some *mental* baggages that go with them are bad... Can those kinds of things be written in other languages than C? Sure. But they can *not* be written by people who think the "high-level" capabilities of C++ string handling somehow matter. The fact is, that is *exactly* the kinds of things that C excels at. Not just as a language, but as a required *mentality*. One of the great strengths of C is that it doesn't make you think of your program as anything high-level. It's what makes you apparently prefer other languages, but the thing is, from a git standpoint, "high level" is exactly the wrong thing.
- ↑ Andrei Alexandrescu. "Iterators Must Go" (PDF).
- ↑ Andrei Alexandrescu. "Generic Programming Must Go" (PDF).
- ↑ Meyers, Scott (2014-12-05). Effective Modern C++: 42 Specific Ways to Improve Your Use of C++11 and C++14 (1 edition ed.). O'Reilly Media. ISBN 9781491903995.
- ↑ "LLVM Coding Standards — LLVM 3.9 documentation". llvm.org. Retrieved 2016-05-04.
- ↑ "LLVM Coding Standards — LLVM 3.9 documentation". llvm.org. Retrieved 2016-05-04.
- ↑ Scott Meyers. "Thoughts on the Vagaries of C++ Initialization".
- ↑ "Do not use Braced Initializer Lists to Call a Constructor".
- ↑ "How can I handle a destructor that fails?".
- ↑ Bjarne Stroustrup. "Foundations of C++" (PDF).
- ↑ "Do not use RTTI or Exceptions".
- ↑ "std::basic_string".
- ↑ "QString".
- ↑ "std::basic_string::length".
For std::string, the elements are bytes (objects of type char), which are not the same as characters if a multibyte encoding such as UTF-8 is used.
- ↑ "<ctype.h>".
- ↑ "Variable-length arrays".
GCC and C99 allow an array's size to be determined at run time. This extension is not permitted in standard C++. However, Clang supports such variable length arrays in very limited circumstances for compatibility with GNU C and C99 programs
External links
- The problems with C++
- C++ The COBOL of the 90s
- C++ is Good for the Economy, It Creates Jobs!
- Why should I have written ZeroMQ in C, not C++