New Pluralsight Course on C++ Standard Library Containers

My new Pluralsight course on C++ Standard Library Containers is live!

In this course, you’ll learn how to use some important containers implemented in the C++ Standard Library, with a combination of theoretical introduction using slides, and practical C++ implementation code, including analyzing and fixing some common bugs.

Comparing the memory layout of std::list vs. std::vector.
Comparing the memory layout of std::list vs. std::vector.

C++ Standard Library implementations offer high-quality well-tested and highly-optimized standard containers, that are very powerful tools when developing software written in C++.

In particular, I’ll discuss std::vector (which is a Standard Library workhorse), std::array, and std::list, including how to use them, discussing their pros and cons, and giving some guidance on picking one or the other, based on the problem at hand. Other containers (e.g. std::map) will be the topic of follow-up courses.

No prior knowledge of C++ Standard Library containers is required. You only need a basic knowledge of C++ language features.

Working on the implementation of a case-insensitive string search.
Working on the implementation of a case-insensitive string search.

Containers and algorithms are kind of like “bread and butter”, so in this course you’ll also learn about the C++ Standard Library design based on the teamwork between containers, iterators and algorithms, and you’ll see how to perform important operations on containers leveraging some useful algorithms already implemented in the C++ Standard Library.

Explaining the erase-remove idiom.
Explaining the erase-remove idiom.

Note that this course is both theory and practice! In fact, I’ll show practical demo code, and I’ll also discuss some bugs that are especially common for those who are just starting to learn the C++ Standard Library’s containers.

Analyzing a subtle bug when working with std::list.
Analyzing a subtle bug when working with std::list.

These are some feedback notes from my reviewers:

The narration is clear, animated, and engaging. The visuals are particularly helpful. [Peer Review]

You do a particularly good job clearly stating the problem here (and elsewhere) so that the solution, when it comes, makes sense and fits nicely. [Peer Review]

Great simple example of undefined behavior to reinforce the concepts you’ve introduced as well as a bonus of uncovering a security issue. [Peer Review]

Very nice module with good examples. Also excellent visuals when describing list, vectors and the various operations. [Peer Review]

Very nice discussion of the trade-offs between a linked list and a vector [Peer Review]

Nice use of a bug to teach a key concept [Peer Review]


Starting from this course page, you can freely play the course overview, and read a more detailed course description and the table of content.

Let me also express my gratitude to all the Pluralsight persons involved in the production of this course: It’s always a pleasure to work with you all!

I hope you’ll enjoy watching this course!


New Pluralsight Course: Introduction to Data Structures and Algorithms in C++

A new course of mine was published in the Pluralsight library: Introduction to Data Structures and Algorithms in C++.

In this course, you’ll learn how to implement some fundamental data structures and algorithms in C++ from scratch, with a combination of theoretical introduction using slides, and practical C++ implementation code.

Introducing the stack with an interesting metaphor

No prior data structure or algorithm theory knowledge is required. You only need a basic knowledge of C++ language features (please watch the “Prerequisites” clip in the first module for more details about that).

Explaining linear search using slides

During this course journey, you’ll also learn some practical C++ coding techniques (ranging from move semantic optimization, to proper safe array copying techniques, insertion operator overloading, etc.) that you’ll be able to use in your own C++ projects, as well.

So, this course is both theory and practice!

Spotting a subtle bug

Here’s just a couple of feedback notes from my reviewers:

The callouts are helpful and keep the demo engaging as you explain the code. [Peer Review]

To say that this is an excellent explanation of Big-O notation would be an understatement. The way you illustrate and explain it is far better than the way it was taught to me in college! [Peer Review]

Big-O doesn’t have to be boring!

Starting from this course page, you can freely play the course overview, and read a more detailed course description and table of content.

I hope you’ll enjoy watching this course!


C++ String Guidance

Last time, I enumerated a few types of strings available in C++.

These days, I’d suggest as the default option for cross-platform standard C++ code to use std::string, storing UTF-8-encoded text inside it. Note that pure ASCII is a proper subset of UTF-8, so storing pure ASCII text in std::string objects is just fine.

In addition, for those platform-specific sections of C++ code, I’d suggest using whatever string class and encoding are typical and “natural” for that platform. For example, at the Windows API boundary, use the UTF-16 encoding, and the std::wstring class in C++ code that doesn’t use ATL or MFC.

In addition, in C++ Windows-specific code that already uses ATL or MFC, another option is to use CString (or the explicit CStringW) enabling Visual Studio Unicode builds (“Configuration Properties” | “General” | “Character Set”: “Use Unicode Character Set”, which has been the default since probably Visual Studio 2005).

On the other hand, Qt-based C++ code can use the QString class, and so on.


How Many Strings Does C++ Have?

(…OK, a language lawyer would nitpick suggesting “How many string types…”, but I wanted a catchier title.)

So, if you program in Python and you see something enclosed by either single quotes or double quotes, you have a string:

s = 'Connie'

Something similar happens in Java, with string literals like “Connie” implemented as instances of the java.lang.String class:

String s = "Connie";

All right.

Now, let’s enter – drumroll, please – The Realm of C++! And the fun begins 😊

So, let’s consider this simple line of C++ code:

auto s1 = "Connie";

What is the type of s1?

std::string? A char[7] array? (Hey, “Connie” is six characters, but don’t forget the terminating NUL!)

…Something else?

So, you can use your favorite IDE, and hover over the variable name, and get the deduced type. Visual Studio C++ IntelliSense suggests it’s “const char*”. Wow!

Visual Studio IntelliSense deduces const char pointer.

And what about “Connie”s?

auto s2 = "Connie"s;

No, it’s not the plural of “Connie”. And it’s not a malformed Saxon genitive either. This time s2 is of type std::string! Thank you operator””s introduced in C++14!

Visual Studio IntelliSense deduces std::string

But, are we done? Of course, not! Don’t forget: It’s C++! 😊

For example, you can have u8”Connie”, which represents a UTF-8 literal. And, of course, we need a thread on StackOverflow to figure out “How are u8-literals supposed to work?”

And don’t forget L”Connie”, u”Connie” and U”Connie”, which represent const wchar_t*, const char16_t* (UTF-16 encoded) and const char32_t* (UTF-32 encoded) respectively.

Now we are done, right? Not yet!

In fact, you can combine the previous prefixes with the standard s-suffix, for example: L”Connie”s is a std::wstring! U”Connie”s is a std::u32string. And so on.

Done, right? Not yet!! In fact, there are raw string literals to consider, too. For example: R”(C:\Path\To\Connie)”, which is a const char* to “C:\Path\To\Connie” (well, this saves you escaping \ with \\).

And don’t forget the combinations of raw string literals with the above prefixes and optionally the standard s-suffix, as well: LR”(C:\Path\To\Connie)”, UR”(C:\Path\To\Connie)”, LR”(C:\Path\To\Connie)”s, UR”(C:\Path\To\Connie)”s, and more!

Oh, and in addition to the standard std::string class, and other standard std::basic_string-based typedefs (e.g. std::wstring, std::u16string, std::u32string, etc.), there are platform/library specific string classes, like ATL/MFC’s CString, CStringA and CStringW. And Qt brings QString to the table. And wxWidgets does the same with its wxString.

Wow! And I would not be surprised if I missed some other string variation out 😊

P.S. With all this string variety (maybe too much…), what about adding to the C++ Standard Library some convenient functions for at least common string operations like trimming spaces and converting strings to upper case and lower case? All in all, C++ does already have rocket-science stuff like Bessel functions in its Standard Library. While, back in the old MFC days, CString already offered convenient methods like Trim, MakeLower and MakeUpper, just to name a few.

Sample slide: Introducing the std::string class
Sample slide: Introducing the std::string class

If you want to learn modern C++ from scratch, in a fun and interesting way, with engaging slides and demo code, please check out my course!

Is Your “C++11 from Scratch” Course Still Valid Today? Yes, Absolutely!

I’m very proud of my “C++11 from Scratch” course published by Pluralsight.

We are in 2018, and there have been C++14 and C++17 in the meantime. So, a legit question is: “Does it make sense for me to watch your C++11 course today for a beginner-oriented introduction to C++?” And the answer is a BIG STRONG YES! 😊

In fact, in that course you will learn modern C++ topics that are valid in both C++11, and also in next versions of the language. For example, what you will learn about the parameter passing rules, like passing by reference vs. passing by value, is perfectly valid in C++11, C++14, and C++17 as well.

Moreover, the practical introductions I gave to standard library’s classes like std::string, or std::vector, and to the std::sort algorithm, just to name a few, are totally valid also in C++14 and C++17.

Similarly, my discussions on defining custom types, constructors, destructor, the RAII pattern and the scope-based lifetime of objects are still valid in C++14 and C++17, as well.

Maybe a better title for that course would be “Modern C++ from Scratch”. Anyway, the content is already there, available for an enjoyable learning experience, with a mix of slides containing interesting visuals, and demo code.

Sample slide: Introducing the std::string class
Sample slide: Introducing the std::string class

And, if you are already familiar with C++11, you may enjoy my follow-up course on “Practical C++14 and C++17 Features”.

Happy learning!


New Pluralsight Course: Practical C++14 and C++17 Features

A new course of mine was published in the Pluralsight library: Practical C++14 and C++17 Features.

From the course short description:

C++14 and C++17 added many new features to the C++ language. This course will teach you practical features introduced in C++14 and C++17, that you will be able to use to write clearer, simpler, and higher-quality modern C++ code.

You can take this course to learn about practical features added in C++14 and C++17, ranging from syntactic sugar like digit separators, to more substantial features like polymorphic lambdas (this course will offer an introduction to basic lambdas as well), relaxed constexpr functions, the Chrono library with its standard-defined duration suffixes, and C++17 juice ranging from nested namespaces, variable declarations in if statements, to “constexpr if” and structured bindings, just to name a few.

Building an Italian-to-English dictionary with std::map

I discussed these topics with both slides and demo code, including showing some bugs and how to fix them.

Demo: Sorting by string length using lambdas

You can watch the course trailer and read a more detailed course description and the table of content starting from this course page.

Proper unit conversions are important!

I put the discussed features in proper context for learners who are already familiar with basic elements of C++11. For example, when I introduced C++14 std::make_unique, I also talked about smart pointers and introduced std::unique_ptr as well. If you need an introduction to basic elements of modern C++, you can take my “C++11 from Scratch” course.

Here’s some feedback from my reviewers:

You’ve done an excellent job with the animated shapes/callouts throughout the module. They really help me to follow along with the narrative explanations. [Peer Review]

The content is logically organized and chunked into bite-size clips. I also like your mix of slides and demos. [Peer Review]

This is an excellent challenge to the viewer to spot the bug in the code. [Peer Review]

Overall, a strong module that will be well-received by an intermediate audience. The explanations are clear and the concepts build on each other, making it easy to follow along. Keep up the great work! [Peer Review]

Raw owning pointers are radioactive!

Thank You

Writing and producing this course has been an interesting journey and a rewarding experience for me. There are several people who worked with me during this journey and with their contributions helped me producing this quality course. I’d like to thank my ASM (former Editor) Beth Gerard-Hess, my Production Editor Austin Crawford, my Curriculum Director Tod Gentille, my reviewers (both QA and peer), and all the Pluralsight persons who worked on this course project. Thanks also to Stephan T. Lavavej for interesting e-mail conversations that provided good food for thought.

I hope you will enjoy this new course on Practical C++14 and C++17 Features: Happy learning! 😊


Subtle Bug When Converting Strings to Lowercase

Suppose that you want to convert a std::string object to lowercase.

The first thing you would do is probably searching the std::string documentation for a convenient easy simple method named to_lower, or something like that. Unfortunately, there’s nothing like that.

So, you might start developing your own “to_lower” function. A typical implementation I’ve seen of such custom function goes something like this: For each character in the input string, convert it to lowercase invoking std::tolower. In fact, there’s even this sample code on

// From

std::string str_tolower(std::string s) {
    std::transform(s.begin(), s.end(), s.begin(), 
                   [](unsigned char c) { return std::tolower(c); }
    return s;

Well, if you try this code with something like str_tolower(“Connie”), everything seems to work fine, and you get “connie” as expected.

Now, since C++ folks like storing UTF-8-encoded text in std::string objects, in some large code base someone happily takes the aforementioned str_tolower function, and invokes it with their lovely UTF-8 strings. Fun ensured! …Well, actually, bugs ensured.

So, the problem is that str_tolower, under the hood, calls std::tolower on each char in the input string. While this works fine for pure ASCII strings like “Connie”, such code is a bug farm for UTF-8 strings. In fact, UTF-8 is a variable-width character encoding. So, there are some Unicode “characters” (code points) that are encoded in UTF-8 using one byte, while other characters are encoded using two bytes, and so on, up to four bytes. The poor std::tolower has no clue of such UTF-8 encoding features, so it innocently spits out wrong results, char by char.

For example, I tried invoking the above function on “PERCHÉ” (the last character is the Unicode U+00C9 LATIN CAPITAL LETTER E WITH ACUTE, encoded in UTF-8 as the two-byte sequence 0xC3 0x89), and the result I got was “perchÉ” instead of the expected “perché” (é is Unicode U+00E9, LATIN SMALL LETTER E WITH ACUTE). So, the pure ASCII characters in the input string were all correctly converted to lowercase, but the final non-ASCII character wasn’t.

Actually, it’s not the std::tolower function: It’s that this function was misused, invoking it in a way that the function was not designed for.

This is one of the perils of taking std::string-based C++ code that initially worked with ASCII strings, and thoughtlessly reuse it for UTF-8-encoded text.

In fact, we saw a very similar bug in a previous blog post.

So, how can you fix that problem? Well, a portable way is using the ICU library with its icu::UnicodeString class and its toLower method.

On the other hand, if you are writing Windows-specific C++ code, you can use the LcMapStringEx API. Note that this function uses the UTF-16 encoding (as almost all Windows Unicode APIs do). So, if you have UTF-8-encoded text stored in std::string objects, you first have to convert it from UTF-8 to UTF-16, then invoke the aforementioned API, and finally convert the UTF-16-encoded result back to UTF-8. For these UTF-8/UTF-16 conversions, you may find my MSDN Magazine article on “Unicode Encoding Conversions with STL Strings and Win32 APIs” interesting.


The CStringW with wcout Bug Under the Hood

I discussed in a previous blog post a subtle bug involving CStringW and wcout, and later I showed how to fix it.

In this blog post, I’d like to discuss in more details what’s happening under the hood, and what triggers that bug.

Well, to understand the dynamics of that bug, you can consider the following simplified case of a function and a function template, implemented like this:

void f(const void*) {
  cout << "f(const void*)\n";

template <typename CharT> 
void f(const CharT*) {
  cout << "f(const CharT*)\n";

If s is a CStringW object, and you write f(s), which function will be invoked?

Well, you can write a simple compilable code containing these two functions, the required headers, and a simple main implementation like this:

int main() {
  CStringW s = L"Connie";

Then compile it, and observe the output. You know, printf-debugging™ is so cool! 🙂

Well, you’ll see that the program outputs “f(const void*)”. This means that the first function (the non-templated one, taking a const void*), is invoked.

So, why did the C++ compiler choose that overload? Why not f(const wchar_t*), synthesized from the second function template?

Well, the answer is in the rules that C++ compilers follow when doing template argument deduction. In particular, when deducing template arguments, the implicit conversions are not considered. So, in this case, the implicit CStringW conversion to const wchar_t* is not considered.

So, when overload resolution happens later, the only candidate available is f(const void*). Now, the implicit CStringW conversion to const wchar_t* is considered, and the first function is invoked.

Out of curiosity, if you comment out the first function, you’ll get a compiler error. MSVC complains with a message like this:

error C2672: ‘f’: no matching overloaded function found

error C2784: ‘void f(const CharT *)’: could not deduce template argument for ‘const CharT *’ from ‘ATL::CStringW’

The message is clear (almost…): “Could not deduce template argument for const CharT* from CStringW”: that’s because implicit conversions like this are not considered when deducing template arguments.

Well, what I’ve described above in a simplified case is basically what happens in the slightly more complex case of wcout.

wcout is an instance of wostream. wostream is declared in <iosfwd> as:

typedef basic_ostream<wchar_t, char_traits<wchar_t>> wostream;

Instead of the initial function f, in this case you have operator<<. In particular, here the candidates are an operator<< overload that is a member function of basic_ostream:

basic_ostream& basic_ostream::operator<<(const void *_Val)

and a template non-member function:

template<class _Elem, class _Traits> 
inline basic_ostream<_Elem, _Traits>& 
operator<<(basic_ostream<_Elem, _Traits>& _Ostr, const _Elem *_Val)

(This code is edited from the <ostream> standard header that comes with MSVC.)

When you write code like “wcout << s” (for a CStringW s), the implicit conversion from CStringW to const wchar_t* is not considered during template argument deduction. Then, overload resolution picks the basic_ostream::operator<<(const void*) member function (corresponding to the first f in the initial simplified case), so the string’s address is printed via this “const void*” overload (instead of the string itself).

On the other hand, when CStringW::GetString is explicitly invoked (as in “wcout << s.GetString()”), the compiler successfully deduces the template arguments for the non-member operator<< (deducing wchar_t for _Elem). And this operator<<(wostream&, const wchar_t*) prints the expected wchar_t string.

I know… There are aspects of C++ templates that are not easy.


Subtle Bug with std::min/max Function Templates

Suppose you have a function f that returns a double, and you want to store in a variable the value of this function, if this a positive number, or zero if the return value is negative. This line of C++ code tries to do that:

double x = std::max(0, f(/* something */));

Unfortunately, this apparently innocent code won’t compile!

The error message produced by VS2015’s MSVC compiler is not very clear, as often with C++ code involving templates.

So, what’s the problem with that code?

The problem is that the std::max function template is declared something like this:

template <typename T> 
const T& max(const T& a, const T& b)

If you look at the initial code invoking std::max, the first argument is of type int; the second argument is of type double (i.e. the return type of f).

Now, if you look at the declaration of std::max, you’ll see that both parameters are expected to be of the same type T. So, the C++ compiler complains as it’s unable to deduce the type of T in the code calling std::max: should T be int or double?

This ambiguity triggers a compile-time error.

To fix this error, you can use the double literal 0.0 instead of 0.

And, what if instead of 0 there’s a variable of type int?

Well, in this case you can either static_cast that variable to double:

double x = std::max(static_cast<double>(n), f(/* something */));

or, as an alternative, you can explicitly specify the double template type for std::max:

double x = std::max<double>(n, f(/* something */));

Learning Modern C++ from Scratch

C++ is a language having a reputation of being hard to learn.

In this C++ course of mine published by Pluralsight, I did my best to prove the opposite: C++ can be learned in a simple, interesting, and fun way!

I used a variety of engaging visuals, metaphors and example demo code to try to teach modern, clear, good C++ from scratch, from the beginning, without any previous programming knowledge.

And, even if you already know C++, you may have fun watching this course as well.

Note: The table of contents and a brief course overview are freely available in the course page.

Sample slide: Iterating through vector elements
Sample slide: Iterating through std::vector’s elements

Here’s some of what my reviewers wrote about this course:

You sound really passionate about this technology.  It comes across in the narration and it’s quite infectious.

You’re a very talented teacher, offering lots of examples, analogies and stories that make the concepts easy to grasp.  The visuals are also really helpful for understanding the concepts.

Overall, I really enjoyed this module.  The content is logically structured, you do a great job explaining the concepts, supported by engaging visuals.  There’s also a nice mix of theory and demos.  You clearly understand your beginner audience, the knowledge they currently have, and how to lead them to a deeper understanding of this technology.  Bravo!

The demo showing the bug with implementing the swap function was excellent. It immediately reinforced your earlier lesson on the scope of local variables.

Fantastic use of Camtasia callouts in the demos.

Sample slide: Introducing the std::string class
Sample slide: Introducing the std::string class

I’d like to sincerely thank Mike Woodring of Pluralsight for approving this course idea, my fantastic editor Beth Gerard-Hess for her continuous encouragement and support during this course production (working with Beth is an absolute pleasure), Stephan T. Lavavej for interesting email conversations that provided good food for thought, all my reviewers (both peer and QA) for their quality course feedback, and all the Pluralsight persons who worked on this course.

This C++ course has been a work of love for me, I put my heart into it: I hope you will enjoy the result!