San Diego C++ Meetup #42 – September 22 2022

Yet another fun night in San Diego C++ Meetup (sdcppmu).

Recording can be found in our sdcppmu Youtube channel.

sdcppmu #42

Here is the agenda link:

https://www.meetup.com/san-diego-cpp/events/288596469/

We had quiz, C++ book which is https://www.amazon.com/Template-Metaprogramming-everything-templates-metaprogramming/dp/1803243457

We also discussed life time extension in the context of C++11 range for loop.

One thing that we discovered during the meeting is MSVC non-conformance with binding RValue to a non const reference. See the twitter discussion here: https://twitter.com/kobi_ca/status/1573155334696628224?s=20&t=2LZMv2JdfxLcbE7piQ76tA

Enjoy the recording!

Kobi

Modern C++ Coding Standard by Marcus Tomlinson – book review

By Yacob (Kobi) Cohen-Arazi

I have this habit of buying books. Like tons of books. Ask my wife, she’ll tell you. I think at that point she gave up.

I like to read what others think about the industry, about a specific domain. How do people see programming (especially C++) and technology from their own perspective.

So sometimes, I get to buy some not-so-familiar-books. This time it was “Modern C++ Coding Standards” by Marcus Tomlinson.

In the book, Marcus is saying that he wanted to share a handful of simple guidelines and best practices that he has been using in producing solid C++ projects over the past few years. And I do think he succeeded in this goal.

I’d start off by stating that the book is short. Easy to read in just couple hours. Not a lot of code snippets, so it’s pretty light. Very easy to quickly digest.

The book starts with one of the best features of C++ – RAII – C++ resource management mechanism. It explains the benefits of this important feature, not only in the context of Memory but also in the context of general resource management and cleanups at the end of a scope.

There are total of 3 parts in the book. Each has few chapters.

Part one (Modern C++ Coding Standards), Chapter One talks about how headers should be written. Couple things that I’m kinda disagreeing on, or at least on the fence:

  1. #pragma once – I’m leaning towards what the standard dictates vs the “less typing” approach. Yes, most likely you are working with a compiler that would have no issues with “#pragma once” but again – it’s not standard (yet?).
  2. Defining special member functions even though you do not have to. For example destructors. Even writing explicit =delete when not needed is something that I would not advise or at least I do not do it in my own code base.

Other than these two, there are plenty of well written points that I’m 100% on board with. I’m not going to list it here since the list is kinda big for a short blog post but I do suggest you go over it and see if you are aligned with each. I believe most of us would be.

Chapter two of the same Part One talks about organizing your cpp files. Again, plenty of good rules that I found very easy to read and digest. I believe most of the readers would find this part useful as well. As in the previous chapter, I have disagreement with one item – organizing the include headers. I’m in the camp of organizing the headers from the more general ones to the more specific ones. For example – your OS headers, then standard lib, 3rd party, your project. I find this order to be less disruptive and pretty solid when it comes to possible errors coming from your own project or 3rdparty headers.

Chapter three talks about Application Sources. Basically where your main() function lives. Lots of good suggestions like using std::future when appropriate, how to use std::async and similar. Just a reminder – the book is not going into details of the “why” but rather stays on the “trust me, you should do what I say/preach”. The bullets on auto, smart pointers and typedef vs “using” vs #define is spot-on.

Part Two is named “Language Agnostic Best Practices”. Chapter Four includes a set of very well written recommendations on how to construct your build system, automating the boring stuff (also great book … on Python), warning levels, static analyzer, version control, formatting etc… I felt like this is a really good list that should be applied to any Software project, regardless the programming language.

Part Three talks about “Templates & Compile-Time Programming”. Chapter five provides a short intro into Templates. I was pleasantly surprised to see C++20 code in this chapter. I.e. seeing concepts described as an advantage when used with Templates. Same warm feeling seeing C++20 related Lambda syntax. Overall, a very good Template introduction squeezed into just a few pages. While there are almost no real recommendations here in terms of coding standards but rather a C++ Class/Function Templates overview, I did find one good recommendation – Avoid specialization function templates and prefer overloading. Good one!

Chapter Six describes Template parameters. Again, not many recommendations but rather a good, concise overview on Template parameters. It covers Type Template parameters and also Non type as well as Template Template Parameters.

Chapter Seven, named “Beyond Templates” explains compile-time programming. It’s a very short chapter that describes the main idea behind constexpr and consteval (again, nice to see C++20 syntax).

The last part of the book provides an excellent summary of the points touched upon in the book. Basically, one can skip the entire first 86 pages and jump directly into the summary and just read, absorb and adapt (modulo the few disagreements that I and maybe others might have).

Overall, an affordably priced book, short (less than 100 pages long) but has good set of recommendations that should work for most, if not all, of us, Modern C++ programmers.

And Marcus – if you are reading this – great job! 🙂

San Diego C++ Meetup #41

Super fun evening in San Diego, America’s finest city with the finest programming language (C++, if you had any doubts).

We learned tons of stuff and we are ready to Rock’n Roll using C++ at work and … home!

What did we discuss tonight?
1. Goals we would like to achieve in San Diego C++ Meetup. We would like to make sure members learn new fun constructs in C++.
2. C++ Quiz – few fun questions.
3. Template Function specialization (Beginners-Intermediate).
4. Correct way to printf() – Using std::string_view with printf (Beginners).

San Diego C++ Meetup #40

Yet another fun evening in San Diego, America’s finest city with the finest programming language.

We discussed:

  1. Welcome slides – goals we would like to achieve in San Diego C++ Meetup
  2. C++ Quiz – few fun questions
  3. Going over C++ Stackoverflow posts
  4. unique_ptr, shared_ptr and std::initializer_list<>

San Diego C++ Meetup #39 Featuring Nick Ristuccia from JFrog and the Conan team!

From the Command Line, to Make, to CMake, to Conan By Nick Ristuccia from JFrog!

This session examines the layers of tooling used to produce C/C++ applications and make developers’ lives easier. Surveys say a major pain point facing C/C++ developers is long build times. One way to save time is to only re-build an artifact when a change occurs. Although the command line offers the precision of specifying what to build, doing this and tracking changes manually can quickly become a daunting and error-prone proposition. Make as a build system allows developers to specify and execute command-line statements depending on what file changes are detected. However, these statements may be particular to one compiler or operating system. CMake provides the missing flexibility for a makefile file. One CMake file can generate what’s needed for a variety of build systems, compilers, and operating systems. Another major pain point facing C/C++ developers is managing all the libraries needed by an application. Libraries provide the functionality programs need. But it gets tricky when libraries depend on other libraries that depend on other libraries in a spaghetti-like formation. The goal of Conan as a package manager is to alleviate this burden. ConanCenter, for example, features over 1000 recipes. The promise of a recipe is to untangle the spaghetti and list the dependencies for a given library.

Nick started in the video games industry, developing titles for console and mobile. Disappointed by the oppressive corporate feel of traditional technical training, Nick’s passion is to create more engaging and powerful learning experiences through game-based learning and other playful techniques. As a Curriculum Developer at Oracle, he focused on Java programming and certification. As a Developer Advocate at JFrog, his focus is on C++, Conan, and other JFrog technologies.

Recording:

San Diego C++ Meetup #38 Featuring Amir Kirsh from Incredibuild

Meetup session May 24 20212

Six ways for implementing max: a walk through API design, dangling references and C++20 constraints

Abstract:
API design in C++ is harder than in other languages, as the lifetime of the arguments and return value shall be considered carefully. While it gives programmers the full power in expressing their intent, it raises all sorts of concerns that should be considered. In this talk we would analyze a very simple function: max, we would see that selecting the proper API is not as simple as it may seem and discuss several alternatives. The discussion would take us through lvalue, rvalue and forwarding references, the rules of moving from a local, variadic templates design, the differences between returning auto and decltype(auto) and C++20 constraints.

Bio:
Amir Kirsh is a C++ lecturer at the Academic College of Tel-Aviv-Yaffo and Dev Advocate at Incredibuild. He is also the Co-organizer of Core C++ conference and a member of the Israeli ISO C++ NB.

Meeting event: https://www.meetup.com/San-Diego-CPP/events/285561768/

Recording:

Use case of utilizing std::set instead of std::map

Some time back I reviewed code that had the following design and data structure:

Now, the above is a struct but just imagine it could be a class with private/public sections, a beefy interface and data members.

The author(s) of the code wanted to place it in some data structure that can help retrieve an “Object” using a given “ID”. So they picked the following approach:

Pretty standard data structure. A {key, value} pair where the “key” is the “ID” of the “Object” and the “value” is the “Object” itself. This is not the first time I see such pattern. It is actually quite common in various code trees.

While looking at this piece of code I wonder, can we do better? The “ID” is part of the “Object”, and the requirements are to be able to insert/find values using std::map(*). The “Object”s are ordered by “ID”. My question is – Why do we need to repeat “ID” as a “Key” ?

Before we move forward, let’s compute the current cost:

This prints “sizeof pair 48, object 40, string 32” which means we pay an extra 8 bytes for storing an integer as the “ID”/”Key”. The same integer that is already stored in “Object”.

So the immediate thought is “yes“. We can do better. What if we eliminate the need for a separate “Key” and store the “Object”s in a similar container, that provides us the same requirements/performance(O(x) wise) but with smaller memory footprints?

We have something like this. It is called std::set<> and it has very similar characteristics to std::map<>. std::map<> stores std::pair<T1,T2>. It contains 2 types. std::set<> stores a single type.

So let’s give it a shot:

And we would like to have the same idea. We’d like to lookup number “5”. But std::set<> does not have a subscript operator (“[]”). It does however have “find()” function instead:

There are couple things we need to straighten out before we open the champagne.

First, by default, std::set<> requires less (“<“) operator to be defined for the stored objects. The compiler does not know how to compare “Object”s. We need to teach it. We can pass a compare function, we can use lambda or, we can just implement a simple member function that will help us to compare Objects by IDs.

This is basically fixing the major missing part. Remember that with std::map<> we had simple “int” as a “Key” and the compiler is very capable of generating code to compare “int”s. But not for “Object”s.

There is some wart here that requires discussion. If we want to write something like:

We need to be able to convert an integer to an “Object”. We can do it using a conversion constructor:

Notice the comment. We cannot make it explicit. In most cases, conversion constructor should be marked explicit, but if you actually need the conversion, you would have to pay this trade off. Otherwise, you’d need to write something less “natural” e.g.:

In my opinion this is a trade off that we would need to pay. Unless there are other sane options. For example I could think about having this non-explicit constructor in private section and having a get() friend function accessing it but I’m not sure this worth the effort.

That’s it. I saved you 8 bytes per entry. Keep the change and thank me later!

(*) std::map is probably implemented as a Red-Black Tree with log(N) to find something and O(1) to (re)balance it

Edit: September 29 2022

I recently realized that I could use Heterogeneous lookup and solve the issue I described with the find function. Here is the example:

And now, I can caall my find function in a very natural way:

Bingo!

Templates, Linking and everything in between

Last weekend, San Diego C++ Meetup hosted Andreas Fertig. Andreas presented his excellent talk on “C++ Templates”.

During his talk, one of the attendees asked a question that many, if not all, C++ programmers had asked at least once in their early life as C++ programmers. In this post, I hope it would provide answers to anyone that bumped into this issue before, and for those that haven’t yet 🙂

And the questions goes something like this.

While compiling and linking my C++ application, which happens to use templates, I’m getting a linker error.

To demonstrate this issue here is a simple example:

hpp file (include guard omitted):

Plus, here is a cpp file, that is added to compile line (e.g. via CMakeLists.txt or any other means)

And eventually main():

Just to discover the following linking error:

As mentioned above, I think all (most?) of us had this at least one time in our C++ programming career.

So what makes C++ Templates so special and makes it impossible for us to place a Template class definition in cpp file, compile it and try to call this function?

Before we answer this question, let’s take a step back and understand the compile/linker stages.

To put it simply, there are few steps to compile your C++ code. There’s a preprocessor step, C++ files to object files compilation step and finally, the linker will create a binary – executable or shared library. Creating a static library is just an archive of all of those object files (compilation units) and no linking step is involved in this case – so let’s ignore it for now (linking happens when exe/so is linked with your static lib).

Here is an example for a simple scenario, using non-Templated code:

And your main() would be something like:

And compiling the above would pass without issue. This is really a simple, vanilla example. Let’s inspect what we have on the file-system:

Note the getVal() that is part of the .text section. We have full definition in our compiled object file.

When main() is linked with this object file, the linker is capable of finding this symbol and all is good. Here is how main() object file looks like:

Note the *UND* kobi::MyNonTemplate::getVal() const – fear not! When creating the entire executable the Linker will find the definition and when you inspect the actual binary:

You see? all good. We have kobi::MyNonTemplate::getVal() const in the .text section and both compilation and linking stages completed w/o errors.

Now, let’s inspect what happened with the Templated one.

Here is the compiled .cpp file that contained that template member function definition:

Unlike the non-templated one, there is nothing interesting here!

getVal() does not exist here in any shape or form. So what happened?

Well, to put it simple, Template, and in this case class Template, is just a vehicle, a special syntax in the language for creating concrete types (or functions), concrete definitions. But for this to happen, one would need to:

  1. Ask the compiler to create, instantiate the class type. (same idea for functions btw).
  2. The compiler must have full visibility to the definition at the time of the instantiation. (unless extern template is used – this part is not covered in this article).

When we compiled the class Template in its own “compilation unit” and tried to instantiate this class type (+ calling a member function) inside main(), the compiler (at the point of instantiation) only had the declaration of the member function since we #include <> the header file. The compiler did not see the complete definition. It’s like there is no such definition!

Wait you say – but I have the cpp compiled. True, but remember, there is no spoon! There is no member getVal() function definition compiled into this translation unit!

It’s just bunch of code that no one instantiate when this specific “template” cpp was compiled!

OK. so what can we do? Few options that I will highlight here.

Define the body of the function in the header itself

There are couple ways you can define the function in the class Template header.

We want to do this so when another cpp includes this header, the point of instantiation has full visibility to the definition.

Or, you can leave the class with just function declarations, and have the definition somewhere outside of the class template:

If you check your compiled object with objdump , you’ll see that getVal() is now showing in your .text section.

Oh yes – using the above method, there is no .cpp anymore. You don’t need it and of course, you don’t need to compile it as a standalone .cpp file.

#include your cpp file in your header

Usually when I introduce this method to a junior C++ programmers, it really confuses them. How can you #include<> a .cpp file in your header. Well, I usually explain them that technically, I can #include<> (almost?) anything, and include it anywhere inside headers of C++ files. Not that every such #include<> would make sense, but yes, I can do it. Sue me!

What does it mean to have #include<> of one file within another file. It means the preprocessor will take the file mentioned in the preprocessor directive as #include<> and will just embed it in the overall buffer that will be fed later into the next compilation step. Don’t believe me? No problem. Run your compile line with -E (of course, no need to use -o option and similar) and you’ll become a true believer 🙂 You’ll see the output buffer of the preprocessor and if you have #include<> directives (and we assume that the preprocessor can find those files), you’ll see the content of these files in the output buffer.

So let’s put this knowledge into practice:

And here is your cpp, it would not have a #include<> of the header:

Again, if you check with objdump, you’ll notice getVal() is in the .text section.

But what if I really want to _compile_ my template cpp file?

I said above that it does not really make sense to compile a .cpp Template file. Well, I lied a bit. This is how you explain things in C++, you lie a bit and then, towards the end, you have a twist in the plot.

In some use cases, you might have the following requirements when working with external entities:

  1. You cannot release the definitions of your class (of function) Template. (IP reasons or you just don’t want others to see how bad is your code 😉
  2. You are OK to allow instantiation of only specific types.

In both cases, the mechanism is as described below:

  1. You write your class definition with only the function member declaration in the header.
  2. You write your class function member definition in a separate .cpp. This .cpp will be compiled.
  3. In the above mentioned .cpp, you instantiate this class Template with specific types. The compiler will generate full class type definition at the point of this explicit instantiation. (btw, this is applicable to non-member functions as well).

Example of such .cpp (#include<> of the header omitted):

I have explicit instantiation of this class type for int and float.

and example of usage:

Note that we cannot instantiate and use getVal() of double since we are back to square one with this type. There is no definition available for double!

Note that since the constructor is implicitly generated (and hence available to the compiler and to the linker) , instance of kobi::MyTemplate<double> would compile and link without issue. I just cannot call functions using this instance.

But there is one drawback with this approach.

One of the beautiful parts of class Template is that you only generate code that you actually use. So if, for example, I have other function(s) in the class Template, and I’m using the traditional way to write Templates (i.e. include the definition in the header and NOT having an explicit instantiate the entire class Template with a specific type), then in this case, objdump will only show me what is actually being used. Example:

If your main() does not invoke print() on some MyTemplate<> instance, this function would not show up in the object file!

However, when you explicitly instantiate this class Template with the syntax showed above:

Then, no matter if you are using or not using parts of the class Template, everything will be compiled and be part of the .text section.

Did anyone order code bloat?

Yes, print() will be there even if I did not use it in main() .

Conclusions

The traditional way to write and use Template code is to have the definition visible to the compiler at the time of instantiation. You can use it by inline-ing the definition in the body of the class, or outside of the class. Another approach is to write a .cpp (or any other extension) file that contains definitions of the member function definitions and #include<> it in the header. In all of the above, you do not compile a separate .cpp Template file.

Another approach is to compile a separate .cpp file and explicitly instantiate the class Template with specific types. These are the only types you could use with this class Template. Also, using this approach the compiler will instantiate the entire class member functions regardless of what you actually use. This is different from the traditional approach where the compiler is generating only parts that you actually use.

Function alias vs Function pointer alias

Last weekend (4/4/2021) I was sitting down and working on my San Diego C++ agenda for the 25th upcoming session.

One of things I really like presenting is few riddles from cppquiz.org

I stumbled upon this one: https://cppquiz.org/quiz/question/227 . Simple and easy one.

Here is the code in question:

And the question is what is the output.

So clearly the question is what does the following syntax mean?

Initially, the “using” part looked like an innocent typedef of a function pointer. But is it?

A quick check with cppinsights.io shows the following

Clearly this is not a function pointer typedef, and we are not defining any “f” as a data member.

Instead, we are actually defining a function named as “f” that returns “int” and takes no params.

So when does it look like a function pointer and when it is not?

Here is a small playground cppinsights.io.

And the gist of it is described in the following snippet:

San Diego C++ Meetup

San Diego C++ Meetup 25th meeting featuring JFrog and Conan!

https://www.meetup.com/San-Diego-CPP/
https://www.meetup.com/San-Diego-CPP/events/277115020/

Agenda

Welcome slides – goals we would like to achieve in San Diego C++ Meetup
This meeting – Hosting JFrog: Conan Package Manager for C++ in Practice

If time permits:
* Shout Out to a great C++ blog – “Vorbrodt’s C++ Blog”
* 3 cppquiz questions
* 2 years of San Diego C++ Books recommendations – a recap!
* An additional New book for this month – “Ace the Trading Systems Developer Interview” With an example of one of the questions

Featuring:
* Conan Package Manager for C++ in Practice

The Conan package manager for C++ is useful in both simple and advanced development environments. Join the Conan team to see it in action, with a simple demo using OSS libraries and tools from ConanCenter, and a more complete demo showing how to create and upload a package including different binaries for different platforms to a private repository. Also, learn about many other unique and innovative advanced Conan features along the way.

Jerry Wiltse Bio: Jerry is a member of the Conan development team, and has been dedicated to build engineering for C and C++ since 2016. He is an avid open-source enthusiast but also deeply focused on enterprise development environments. He is also the narrator and creator of the Conan learning track on the JFrog Academy.