Articles & Books

Quick Q: Should we really avoid new and delete? -- StackOverflow

A: Yes, except possibly encapsulated inside the implementations of low-level data structures.

The more general question on SO was:

About the usage of new and delete, and Stroustrup's advice

About the usage of new and delete, and Stroustrup's advice...

He says something like (but not exactly, this is from my notes of his book):

A rule of thumb is that, new belongs in constructors and similar operations, delete belongs in destructors. In addition, new is often used in arguments to resource handles. Otherwise avoid using new and delete, use resource handles (smart pointers) instead.

I was wondering if the more experienced folks with C++11 have really applied this or not.

My impression of this was, wow this seems like a really cool rule to follow. But then I got suspicious, as for any general rule. At the end of the day you will end up using new and delete wherever necessary. But maybe this rule is a good guideline I don't know.

Interlude: C++’s Strides in 2013 -- K-ballo

K-ballo's look at the achievements of C++ completed in 2013 and coming up in 2014, with an overview of draft C++14 features.

Interlude

by K-ballo

From the article:

One year down the road, 2013 has gone by but not without modifications to the C++ lands. Two major compilers have reached C++11 conformance ---GCC and Clang---. Shortly after, the Committee Draft (CD) for C++14 was completed, which is now just around the corner...

All things considered, it was an impressive year for C++ conformance. And notably, it looks like for the first time there will be feature complete compilers for a C++ standard on the very same year it is ratified. The following slide from GoingNative's Keynote: Herb Sutter -- One C++ summarizes the situation nicely:

[... lots of discussion of C++14 features ...]

The C++ lands grew bigger during 2013, and we can only expect this trend to intensify during 2014. With the likely ratification of C++14 and at least some of the TS, it will certainly be a good year for C++.

 

GotW #7b Solution: Minimizing Compile-Time Dependencies, Part 2

The solution to the latest GotW problem is now available.

GotW #7b Solution: Minimizing Compile-Time Dependencies, Part 2

by Herb Sutter

From the article:

Now that the unnecessary headers have been removed, it’s time for Phase 2: How can you limit dependencies on the internals of a class?

... 

Guideline: For widely-included classes whose implementations may change, or to provide ABI-safety or binary compatibility, consider using the compiler-firewall idiom (Pimpl Idiom) to hide implementation details. Use an opaque pointer (a pointer to a declared but undefined class) declared as struct impl; std::unique_ptr<impl> pimpl; to store private nonvirtual members.

Quick Q: Does constexpr guarantee compile-time evaluation? -- StackOverflow

Quick A: constexpr guarantees compile-time evaluation is possible if operating on a compile-time value, and that compile-time evaluation will happen if a compile-time result is needed.

From SO, the originally worded question:

Can C++ constexpr function actually accept non-constant expression as argument?

I have defined a constexpr function as following:

constexpr int foo(int i)
{
    return i*2;
}

And this is what in the main function:

int main()
{
    int i=2;
    cout<<foo(i)<<endl;
    int arr[foo(i)];
    for(int j=0;j<foo(i);j++)
        arr[j]=j;
    for(int j=0;j<foo(i);j++)
        cout<<arr[j]<<" ";
    cout<<endl;
    return 0;
}

The program was compiled under OS X 10.8 with command clang++. I was surprised that the compiler did not produce any error message about foo(i) not being a constant expression, and the compiled program actually worked fine. Why?

Quick Q: How do I use conditional noexcept? -- StackOverflow

The question also has a lemon-zest touch of "templates in headers" but the basic noexcept question is still the same:

Use of the noexcept specifier in function declaration and definition?

Consider the following function:

// Declaration in the .h file
class MyClass
{
    template <class T> void function(T&& x) const;
};

// Definition in the .cpp file
template <class T> void MyClass::function(T&& x) const;

I want to make this function noexcept if the type T is nothrow constructible.

How to do that? (I mean what is the syntax ?)

Quick Q: Does memory layout (including alignment) matter for performance? -- StackOverflow

Quick A: Oh, yeah.

See the nice three-paragaph "highlights" answer to the question:

Does alignment really matter for performance in C++11?

There is an advice in Stroustrup's book to order the members in a struct beginning from the biggest to the smallest. But I wonder if someone has made measurements to actually see if this makes any difference, and if it is worth it to think about when writing code.

A shared view of C++ (or, Around the C++ world in 180 pages)

[Note: There has long been “one short and reasonably complete book you can assume everyone has read” for C -- K&R 2nd Edition (274 pages). But what is the “one short and reasonably complete book you can assume everyone has read” for C++? Does a single short one even exist, and is it possible for one to exist? This post by Bjarne Stroustrup addresses that important question, with what we feel is the year's most important book on C++ -- more important than even the C++11-updated The C++ Programming Language, 4th Ed., also by Stroustrup.

The "(or, Around the C++ world in 180 pages)" alternate title for this blog post is our editorial suggestion, with apologies to both Stroustrup and Jules Verne. We believe this is quite appropriate for Stroustrup's year-end gift to the C++ community. Enjoy. --Ed.]

 

For a graduate course in software design, I needed a few introductory lectures to “refresh” my students’ understanding of C++. For The C++ Programming Language (Fourth Edition), I wrote introductory chapters (about 80 pages) to give the reader an overview of C++ before diving into the details. At the suggestion of Herb Sutter, I posted drafts of those four Tour of C++ chapters on isocpp.org, and at the suggestion of my Addison Wesley editor, Peter Gordon, I expanded these chapters to provide a comprehensive overview of and introduction to C++ (for people who are already programmers, not complete novices):

A Tour of C++

by Bjarne Stroustrup

Addison Wesley, ISBN 978-0321958310, 2013

In 180 pages, it covers the major C++11 features and techniques plus most of the standard library. 180 pages is something most programmers can find the time to read. The tour (Tour++) benefited greatly from use and comments from many readers.

It gradually dawned on me that I just might have produced a solution to a decades-old problem for C++:

What is the basic knowledge that we should be able to assume from a competent C++ programmer?

Competent C programmers can be assumed to know roughly what is covered by K&R. Conversely, if they don’t -- or haven’t even heard of K&R -- it is a good guess that they can’t be relied on to contribute viable C code. I find that I cannot make an equivalent statement about C++ programmers. Once upon a time, knowing TC++PL (1st edition) served as a shared base, but that was a long time ago and C++ has improved immensely since 1985. These days, there are functioning C++ programmers who have learned all they know from the Qt documentation, from boost.org, from Scott Meyers’ many books, from some of my books and papers, from some of Herb Sutter’s books, etc., but don’t know more than one of these sources. Their ideas of what C++ is are disjoint and incompatible. Many more programmers appear to base their understanding of C++ on some ancient, outdated, and usually poor college textbook plus what they learn from on-line documentation and following some C++ Q&A site. But you don’t become a good C++ programmer just by knowing only the C++ syntax and a multitude of library classes and functions. Similarly, being able to answer tricky “interview-style” questions about the ISO standard doesn’t make you a good C++ Programmer.

We -- the huge and diverse C++ communities -- do not share a body of basic understanding. This is bad; very bad! We don’t have a shared view of what good C++ code is and we don’t communicate effectively. I find -- from web posting, from academic papers, from my email, and more -- that huge chunks of the last 20 years of progress in design technique, programming technique, and language support remain unknown and unused by many “C++ programmers.” What a waste! More specifically, what a waste of energy as programmers suffer from outdated parochial views in their current work today! Conversely, what an opportunity for improvement!

Many have tried to address parts of this problem. The sources I mentioned above are not bad, but they are not shared and few are comprehensive. I can and do recommend them often. Further, I recommend the many superb talks from the “Going Native” 2012 and 2013 conferences (freely available on the Web) as well as talks recorded at Google, ACCU, and others. It is not volume of material we lack. On the contrary, it is quite easy to drown in information about C++. Few practicing programmers can keep up with all the quality information being produced. Worse, the quality information is often drowned by the constant deluge of poor, outdated, and often wrong information provided on the web (and elsewhere).

As the risk of being seen as a blatant self-promoter, I would like to recommend A Tour of C++. [We wholeheartedly support this recommendation. --Ed.] For a technical book, it is a quick read, and it is not a waste of time: I have never met a programmer of any experience level who didn’t learn something from reading it. If everyone read it, the C++ community would again -- after something like 25 years -- have a common conceptual framework and vocabulary. Read it! You might even like it.

Thoughts on C++'s future and the pointer

I've written down some thoughts on the future of C++ and the pointer:

C++ future and the pointer

From the Article:

The last weeks after Meeting C++ 2013 I've been thinking a lot about C++, and also a little bit about pointers. While C++11 brought only little changes for pointers (nullptr f.e.), the semantics and usage of pointers in C++ has changed over the last years.

Quick Q: What is this "C++ memory model" you speak of? -- StackOverflow

Quick A: First read Stroustrup's FAQ answer, before reading the SO answers which are also illuminating. For a deep answer and to really grok this topic, check out Sutter's slides from his three-hour deep-dive talk.

A 2011-vintage "new classic" from SO:

C++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?

... So, what I basically want to know is, C++ programmers used to develop multi-threaded applications even before, so how does it matter if its POSIX threads, or Windows threads, or C++11 threads? What are the benefits? I want to understand the low-level details.

I also get this feeling that the C++11 memory model is somehow related to C++11 multi-threading support, as I often see these two together. If it is, how exactly? Why should they be related?

As I don't know how internals of multi-threading works, and what memory model means in general, please help me understand these concepts. grin