Prefer nonmember, nonfriends?

How many member functions does std::string have?

As of C++17 the answer is 153, assuming I counted correctly.

One Hundred Fifty Three.

That is a lot. And as Herb Sutter has pointed out, most of those members could easily be implemented as non-members without loss of performance.

And they should be implemented as nonmembers according to an old guideline from the C++ coding standards: Prefer nonmember, nonfriends. Write free functions whenever possible, not members.

But how true is that advice really?

» read more »
Author's profile picture Jonathan

The year is 2017 - Is the preprocessor still needed in C++?

The C++, eh C, preprocessor is wonderful.

Well, no - it isn’t wonderful.

It is a primitive text replacement tool that must be used to work with C++. But is “must” really true? Most of the usage has become obsolete thanks to new and better C++ language features. And many more features like modules will come soon™. So can we get rid of the preprocessor? And if so, how can we do it?

» read more »
Author's profile picture Jonathan

cppast - A library to parse and work with the C++ AST

Last year I started standardese, a C++ documentation generator. In order to provide exact documentation, I need to parse C++ code. As I didn’t want to waste time implementing my own parser, which will take ages and don’t work most of the time, I opted to use libclang.

libclang is a C API that exposes the C++ abstract syntax tree (AST) which is built on top of clang. And clang is a good and conforming C++ compiler, so I expected an interface to read the AST that just works and give me the information I need.

Well, I was wrong. Here’s why and how I solved it.

» read more »
Author's profile picture Jonathan

std::string_view accepting temporaries: good idea or horrible pitfall?

C++17 brings us std::string_view. It is a really useful tool: If you want to write a function accepting some string, but does not need ownership, i.e. a view, use std::string_view. It supports both const char* and std::string without any work, and does not involve any heap allocations. Further, it clearly signals intent: this function takes a view. It doesn’t own anything, it just views it.

As someone who frequently advocates for using correct types, I am happy about std::string_view. Yet there is one design decisions that warrants a discussion: std::string_view silently views temporaries as well. This can create a problem if the view lives longer than the temporary, as the view now views already destroyed data.

Let’s look into the reasons behind this decision and what that means for using std::string_view.

» read more »
Author's profile picture Jonathan

Advertisement