Krita/C++11
General links about using C++11 in Qt
There have been a few links discussing mixing C++11 with Qt, and starting with Qt 5.6 C++11 support will be default. Note: as would be expected from those interested in hot new technology, the writers of most of these links demonstrate Silicon Valley levels of extreme optimism. Take this with a grain of salt: there is no such thing as a free lunch.
Here are some overviews of C++11 features.
- Bjarne Stroustrup's C++11 FAQ - the grand daddy
- An older, more balanced introduction to several topics
Qt's API design principles do not always overlap with the C++ Standards Committee design principles.
Particular Features
Under "drawbacks," every item should list: "Programmers will face another feature they must learn about."
Type Inference (auto)
Motivation: If a function t has a return type T, it is redundant to write T x = f(y). Using auto declarations is a simplification in two ways scenarios. First, it allows the programmer to write code without worrying about doing the manual type deduction, for example, KoXmlReader::const_iterator x = iter.begin() versus auto x = iter.begin() . Second, it allows the programmer to change the type of a function or class member without changing the declarations of local variables.
Drawbacks: Some uses of auto can be obfuscating. For example, auto x = 2 is not obviously an integer, and auto x = {"a", "b", "c"} returns std::initializer_list.
Recommendation: In general, it is fine to declare a local variable as auto, if it initialized using another variable, or as the return value from a function. Don't use it to initialize constants, and don't let it reduce the clarity of the code.
Range-based for loop
Motivation: This is something a long time coming in C++. It is a standardized replacement for Qt's foreach() construct, which works not only with Qt objects but all iterable C++ types.
for (T x : list ) { }
It will work with standard tooling and static analysis, and is faster by defaulting to in-place access.
Drawbacks: By default, Qt's foreach rewites the code to make a shallow copy and then use const accessors, while c++11 does the opposite, avoiding copying when possible. When using const accessors, this is faster, but if you try to make changes to the data, this will slow your loop down instead.
Recommendation: Sometimes, the range-based for is faster. Sometimes the Qt iterator is faster. Personally I prefer the range-based for, since it works better with static analysis. Also it is always possible to write it in a way that replicates the foreach() behavior, but the reverse is not true.
General Initializer Lists
Motivation: Initializer lists are intended to work in many different places to simplify the syntax for complicated initialization. For example, a list of strings could be initialized const QStringList x = {"abc", "def", "xyz" }; and this would work just fine for a std::list<std::string> as well.
A second place initializer lists are used is in creating standard initial values for class members. This takes the place of writing a lengthy constructor list like f(_q) : String1("a"), Subclass1(0), Subclass2(1).
Mixed uniform initialization is another addition. It is possible to give
Drawbacks: None I can think of. This is super simple, completely obvious to read and write, and shortens code by removing big default constructors.
Recommendation: Yes!
New-style signals/slots, lambdas
Motivation: Lambda expressions are a big new addition for C++11. Many programmers claim they start to feel like an essential part of the language very quickly. One of the biggest uses for lambdas is in the standard algorithm library <algorithm>, which is described below. In Qt5, this, along with std::function and std::bind, allow for One of the most useful C++11 integrations, a new signal/slot syntax which replaces the moc macros SIGNAL() and SLOT() with standard C++. For example:
- connect(sender, SIGNAL (valueChanged(QString,QString)), receiver, SLOT (updateValue(QString)) );
- connect(sender, &Sender::valueChanged, receiver, &Receiver::updateValue );
New style signals and slots provide a great benefit from the tooling perspective: now, all types for functions and function arguments can be checked statically, and you don't have to catch typos by monitoring debug messages saying "no such slot."
Another possibility is to use lambdas directly inside connect(), instead of defining a class member function which is only used once. The greatest benefit is that the function can be defined right where it is used; it also aids readability to get rid of a list of tiny helper functions from the header.
- "Qt5: C++11 lambdas are your friend"
- C++ language reference
- Qt.io New Signal/Slot Syntax Also gives detailed pros/cons.
Drawbacks: The new-style syntax makes it somewhat harder to use default arguments, which requires the use of lambdas. It is also a little less pretty.
Lambdas in general are have become one of the most clunky pieces of C++11 notation. Since they allow a great deal of options (for example, capturing closure variables by reference with [&] versus capturing by value with [=]) they are a significant new addition to the C++ learning curve. Using auto F = [&] ( x ) { whatever } and slinging F around in places is confusing for everyone. Lambdas will not disconnect automatically, although there is a special syntax to make that happen.
Recommendation: The new signal/slot syntax should be encouraged. It is simply easier to write it correctly. Lambdas will feel strange until they're used in many places, at which point they will feel normal. For the time being, they should only be used to replace one-off signals and slots, and inside <algorithm>. For consistency's sake, we should try to stick to a single method. I recommend using the new style syntax.
constexpr
Motivation: Performing calculations at compile time can speed things up at runtime. KDAB: speed up your Qt 5 programs using C++11
Drawbacks: Not easy to use these features.
Recommendation: This could be useful in specific places, like KoCompositeOpRegistry. Overall it is not something most programmers will run into.
<algorithm>
Motivation: Using something like std::replace (myvector.cbegin(), myvector.cend(), 20, 99); is more concise, safer and easier to read than a handwritten loop that looks for occurences of the number 20 and replaces it with 99. There should be no performance penalty compared to a hand-written loop on STL classes. A list of standard algorithms can be found here. Historically Qt provided its own algorithm library, but now encourages programmers to use the STL versions instead, and Qt's own algorithm library will mostly become deprecated. http://doc.qt.io/qt-5/qtalgorithms.html Unlike range-based for, since we are easily able to specify constBegin/cbegin, constEnd/cend, using standard algorithms can always be as fast, and generally will be faster, than using Qt foreach loops.
Drawbacks: Some of the standard algorithms are not completely obvious from observing the name. For example, I could not describe the five arguments of std::replace_copy off the top of my head. When values inside the container need to be modified, non-const iterators may be slower than a Qt foreach().
Recommendation: Encourage the use of <algorithm> when it improves code clarity, speed is a secondary concern most of the time, so don't make changes which are harder to understand just for a tiny hypothetical speed boost. Krita's hot paths should be checked and moved to <algorithm> instead of Qt foreach().
enum class
Motivation: These are a type-safe version of enums. This prevents comparison with a Another benefit is that enum classes can be forward-declared. enum class Color; void paint(Color c); enum class Color {Red, Green, Blue};
Drawbacks: Virtually none. Very small changes to the code, more type safety. Existing sloppy code does not necessarily have to be rewritten.
Recommendation: Use enum classes whenever possible.
Local type definitions (i.e. using)
Motivation: An easier and localized way to use typedefs. Can be at the namespace, class, or function level.
Drawbacks: Very few. These are quite intuitive, and allows you to place typedefs closer to where they're used. Recommendation: Go for it.
nullptr
Motivation: The use of nullptr as a default pointer initializer is a very small change in C++11, and mostly an aesthetic one. There are very few things it prevents: for example, it cannot be used in a statement int x = nullptr;, and it cannot be used in a function template like template<class A, class B>. Otherwise, the bigger gain is to point out when you are doing something dangerous, i.e. allowing a potentially null pointer.
Drawbacks: It takes longer to type nullptr than it takes to type 0, and it's not so visually pleasing. Converting the existing code base would be fairly laborious. Tiny benefits.
Recommendation: 100% up to the maintainer's preferences.
Deleted, default, override, final
Motivation: These are keywords used for designing inheritance patterns. They are useful for preventing accidental copy construction.
Drawbacks: Since Krita does not export libraries, most of the time we won't need to worry about these.
Recommendation: No reason to hold back from these features if they seem useful. Dmitry's UML diagrams may become even more exuberant this way.
unique_ptr
Motivation: Here is a glowing review of unique_ptr. This is really about a philosophy of C++ memory management, not just a particular smart pointer type. The idea is that whenever you create an object on the heap, you should always house it inside a smart pointer. The reason this philosophy had to wait for unique_ptr is that unique_ptr is the first time they 'got it right.' Most importantly, the class uses negligible overhead. In particular: sizeof(unique_ptr<T*>) = size_t, it can be passed as a function argument without copying, and dereferencing is inline.
"Rule of Zero": more about the C++ design philosophy behind unique_ptr.
Drawbacks: The philosophy mentioned above can be summarized like this: we should state up front what we are going to prohibit programmers from doing. Like the const keyword, unique_ptr puts restrictions on what can be done with the pointer, the main one being, it cannot be copied. Like enforcing const correctness, this can be annoying to get right throughout a codebase.
One particular limitation is that Qt container classes. For example QVector<std::unique_ptr> is invalid, because QVector requires its members can be copied. This makes converting to unique_ptr a bit slow, since QVector<T *> will have to be converted to std_array<unique_ptr<T*>>. If the owner was being copied before, it will become uncopiable. This can be a good thing, but it can also be extra work.
Moving a unique_ptr requires additional semantics.
Recommendation: I think d_ptrs should almost always be wrapped in a unique_pointer. This removes the need for custom destructors, and eliminating copy constructors is a side benefit. unique_pointer can be useful in other places as well.
(Note: my opinion is that d_ptrs are not very useful for Krita since splitting with Calligra, since it exports no libraries.)
Using move constructors and rvalues are very subtle and advanced features, but widely celebrated as successes of C++11. In general these should be used inside hot paths and when we sling around objects from place to place. C++ programmers should already be aware that writing performant code inside hot paths will sometimes require slinging around ampersands. These features will naturally stay confined to the corners of the codebase where they belong, and should be introduced when they are useful.
- Tutorial for rvalue references
- KDAB: speed up your Qt 5 programs using C++11
- Slide 37 gives a nice chart describing lvalue/rvalue types in exact detail
Move Constructors
Recommendation: Use whenever it aids performance.
Reference Qualifiers
Recommendation: Use whenever it aids performance.
C++11 features mostly for template programming
Krita makes very light use of templates. These features are useful, coming across them in the code base will add complexity for new learners, and have not been necessary so far.
- decltype : this is the most likely of these features to be useful, for example, in KisInputManager.
- static_assert
- variadic templates
Other C++11 features that will not be useful
- Threads (Qt/KDE uses its own threading model, not C++ threading model)
- shared_ptr and weak_ptr (Relies on C++ threading model; use KisSharedPointer)
- New literal types (already have QString)
- Extended Unions (already have QVariant)