Articles & Books

Stroustrup's Tour of C++: Third chapter posted

Part 3 of Bjarne Stroustrup's draft Tour of C++ is now available. This material is a preview draft of Chapter 4 of Stroustrup's upcoming The C++ Programming Language, 4th Edition.

A Tour of C++, Part 3: Containers and Algorithms

by Bjarne Stroustrup

Stroustrup writes:

No significant program is written in just a bare programming language,
it would be too tedious.

However, just about any task can be rendered simple by the use of good libraries.

This third chapter of my tour of C++ begins the presentation of the standard library, which is about half of the C++ standard.

Constructive comments would be most welcome.

Preconditions, Part 1 -- Andrzej KrzemieĊ„ski

On preconditions, and their compile time enforcement with static_assert and a dash of regex.

Preconditions, Part 1

by Andrzej Krzemieński

In this post, I want to share my thoughts about the notion of precondition. In “Design by Contract” philosophy, preconditions are always mentioned along postconditions and invariants, and in the context of OO design. In this post I focus only on preconditions and not necessarily related to any class. For instance, the following function specifies a precondition on its argument:

double sqrt(double x);

// precondition: x >= 0

Note that the function specifies the precondition even though there is no language feature for this purpose (at least in C++). A precondition is a “concept” or an “idea” rather than a language feature. This is the kind of preconditions that this post is about.

Continue reading...

Using constexpr to Improve Security, Performance and Encapsulation in C++ -- Danny Kalev

How is constexpr different from const, and how does it contribute to making modern C++ code cleaner and simpler, as well as faster than ever? Danny Kalev gives a nice summary:

Using constexpr to Improve Security, Performance and Encapsulation in C++

by Danny Kalev

constexpr is a new C++11 keyword that rids you of the need to create macros and hardcoded literals. It also guarantees, under certain conditions, that objects undergo static initialization. Danny Kalev shows how to embed constexpr in C++ applications to define constant expressions that might not be so constant otherwise.

Continue reading...

Quick Q: A unique_ptr is not copyable, so why can I return one by value? -- StackOverflow

 

A common question for programmers new to C++11 and its new features: "Hey, look how easy this was! ... But, um, why and how did it work?"

Returning unique_ptr from functions

unique_ptr<T> does not allow copy construction, instead it supports move semantics. Yet, I can return a unique_ptr<T> from a function and assign the returned value to a variable.

#include <iostream>
#include <memory>
using namespace std;

unique_ptr<int> foo()
{
  unique_ptr<int> p( new int(10) );
  return p;                   // 1
  //return move( p );         // 2
}

int main()
{
  unique_ptr<int> p = foo();
  cout << *p << endl;
  return 0;
}

The code above compiles and works as intended. So how is it that line 1 doesn't invoke the copy constructor and result in compiler errors? If I had to use line 2 instead it'd make sense (using line 2 works as well, but we're not required to do so).

I know C++0x allows this exception to unique_ptr since the return value is a temporary object that will be destroyed as soon as the function exits, thus guaranteeing the uniqueness of the returned pointer. I'm curious about how this is implemented, is it special cased in the compiler or is there some other clause in the language specification that this exploits?

Continue reading...

C++11: A cheat sheet -- Alex Sinyakov

Want a quick "cheat sheet" overview of what's new in C++11? Alex Sinyakov recently gave a presentation on this topic and has posted slides that are useful as a capsule summary in flash card form:

C++11 (PDF slides)

Alex Sinyakov, AMC Bridge LLC

Slide after slide shows C++11 code side by side with the same code written in older C++ style or in other languages. You'll quickly notice a pattern: In example after example, C++11 code is clean, safe, and as fast as ever... and sometimes even faster.

As Bjarne Stroustrup puts it: "Surprisingly, C++11 feels like a new language: The pieces just fit together better than they used to and I find a higher-level style of programming more natural than before and as efficient as ever."

Enjoy these great quick study notes as a refresher before your next C++11 interview.

For a detailed treatment of what’s new in C++11, see Overview of the New C++ (C++11) by Scott Meyers, featured on our Get Started! page. These are Scott’s fully-annotated color training materials from his course of the same name, and the best current approximation of “a book on what’s new in C++11.” (Free sample available.)

Best of 2012: auto

Perhaps the most common single question about C++11 is: When should we use auto to declare local variables?

Here's a current set of responses on Programmers.StackExchange. Enjoy.

Does auto make C++ code harder to understand?

I saw a conference by Herb Sutter where he encourages every C++ programmer to use auto.

I had to read C# code some time ago where var was extensively used and the code was very hard to understand -- every time var was used I had to check the return type of the right side. Sometimes more than once, because I forgot the type of the variable after a while!

I know the compiler knows the type and I don’t have to write it, but it is widely accepted that we should write code for programmers, not for compilers.

I also know that is more easy to write:

auto x = GetX();

Than:

 

someWeirdTemplate<someOtherVeryLongNameType, ...>::someOtherLongType x = GetX();

But this is written only once and the GetX() return type is checked many times to understand what type x has.

This made me wonder -- does auto make C++ code harder to understand?

Continue reading...

Quick Q: Inserting a variadic argument list into a vector? -- StackOverflow

From StackOverflow [c++11]:

I have an object that needs to take a variadic argument list in its constructor and store the arguments in a vector. How do I initialize a vector from a the arguments of a variadic constructor?

class GenericNode {
public:
    GenericNode(GenericNode*... inputs) {
            /* Something like... */
        // inputs_.push_back(inputs)...;
}
private:
    std::vector<GenericNode*> inputs_;
};

Continue reading...

Quick Q: Simultaneously iterating over and modifying an unordered_set? -- StackOverflow

From StackOverflow [c++11]:

Consider the following code:

unordered_set<T> S = ...;
for (const auto& x : S)
   if (...)
       S.insert(...);

This is broken correct? If we insert something into S then the iterators may be invalidated (due to a rehash), which will break the range-for because under the hood it is using S.begin ... S.end.

Is there some pattern to deal with this?

Continue reading...