Articles & Books

The Problem, The Culprits, The Hope--Tony “Bulldozer00” (BD00) DaSilva

This is another call to all C++ programmers, it is time to change!

The Problem, The Culprits, The Hope

by Tony “Bulldozer00” (BD00) DaSilva

From the article:

Bjarne Stroustrup’s keynote speech at CppCon 2015 was all about writing good C++11/14 code. Although “modern” C++ compilers have been in wide circulation for four years, Bjarne still sees:

I’m not an elite, C++ committee-worthy, programmer, but I can relate to Bjarne’s frustration...

Bitesize Modern C++ : noexcept--Glennan Carnie

What is the use of noexcept?

Bitesize Modern C++ : noexcept

by Glennan Carnie

From the article:

We have some basic problems when trying to define error management in C:

  • There is no “standard” way of reporting errors. Each company / project / programmer has a different approach
  • Given the basic approaches, you cannot guarantee the error will be acted upon.
  • There are difficulties with error propagation; particularly with nested calls.

The C++ exception mechanism gives us a facility to deal with run-time errors or fault conditions that make further execution of a program meaningless...

C++ Core Guidelines -- Bjarne Stroustrup, Herb Sutter

Bjarne Stroustrup and Herb Sutter are currently editing the newly created C++ Core Guidelines on GitHub. 

C++ Core Guidelines

From the abstract section of the page:

This document is a set of guidelines for using C++ well. The aim of this document is to help people to use modern C++ effectively. By "modern C++" we mean C++11 and C++14 (and soon C++17). In other words, what would you like your code to look like in 5 years' time, given that you can start now? In 10 years' time?

The guidelines are focused on relatively higher-level issues, such as interfaces, resource management, memory management, and concurrency. Such rules affect application architecture and library design. Following the rules will lead to code that is statically type safe, has no resource leaks, and catches many more programming logic errors than is common in code today. And it will run fast - you can afford to do things right.

We are less concerned with low-level issues, such as naming conventions and indentation style. However, no topic that can help a programmer is out of bounds.

Our initial set of rules emphasize safety (of various forms) and simplicity. They may very well be too strict. We expect to have to introduce more exceptions to better accommodate real-world needs. We also need more rules.

You will find some of the rules contrary to your expectations or even contrary to your experience. If we haven't suggested you change your coding style in any way, we have failed! Please try to verify or disprove rules! In particular, we'd really like to have some of our rules backed up with measurements or better examples.

You will find some of the rules obvious or even trivial. Please remember that one purpose of a guideline is to help someone who is less experienced or coming from a different background or language to get up to speed.

The rules are designed to be supported by an analysis tool. Violations of rules will be flagged with references (or links) to the relevant rule. We do not expect you to memorize all the rules before trying to write code.

The rules are meant for gradual introduction into a code base. We plan to build tools for that and hope others will too.

Comments and suggestions for improvements are most welcome. We plan to modify and extend this document as our understanding improves and the language and the set of available libraries improve.

 

Quick Q: What is a smart pointer and when should I use one?

Quick A: Pointers that helps you manage memory.

Recently on SO:

What is a smart pointer and when should I use one?

A smart pointer is a class that wraps a 'raw' (or 'bare') C++ pointer, to manage the lifetime of the object being pointed to. There is no single smart pointer type, but all of them try to abstract a 'raw' pointer in a practical way.

Smart pointers should be preferred over 'raw' pointers. If you feel you need to use pointers (first consider if you really do) you would normally want to use a smart pointer as this can alleviate many of the problems with 'raw' pointers, mainly forgetting to delete the object and leaking memory.

With 'raw' C++ pointers, the programmer has to explicitly destroy the object when it is no longer useful.

// Need to create the object to achieve some goal
MyObject* ptr = new MyObject();
ptr->DoSomething(); // Use the object in some way
delete ptr; // Destroy the object. Done with it.
// Wait, what if DoSomething() raises an exception...?

A smart pointer by comparison defines a policy as to when the object is destroyed. You still have to create the object, but you no longer have to worry about destroying it.

SomeSmartPtr<MyObject> ptr(new MyObject());
ptr->DoSomething(); // Use the object in some way.

// Destruction of the object happens, depending
// on the policy the smart pointer class uses.

// Destruction would happen even if DoSomething()
// raises an exception

The simplest policy in use involves the scope of the smart pointer wrapper object, such as implemented by boost::scoped_ptr or std::unique_ptr.

void f()
{
    {
       boost::scoped_ptr<MyObject> ptr(new MyObject());
       ptr->DoSomethingUseful();
    } // boost::scopted_ptr goes out of scope --
      // the MyObject is automatically destroyed.

    // ptr->Oops(); // Compile error: "ptr" not defined
                    // since it is no longer in scope.
}

Note that scoped_ptr instances cannot be copied. This prevents the pointer from being deleted multiple times (incorrectly). You can, however, pass references to it around to other functions you call.

Scoped pointers are useful when you want to tie the lifetime of the object to a particular block of code, or if you embedded it as member data inside another object, the lifetime of that other object. The object exists until the containing block of code is exited, or until the containing object is itself destroyed.

A more complex smart pointer policy involves reference counting the pointer. This does allow the pointer to be copied. When the last "reference" to the object is destroyed, the object is deleted. This policy is implemented by boost::shared_ptr and std::shared_ptr.

void f()
{
    typedef std::tr1::shared_ptr<MyObject> MyObjectPtr; // Nice short alias.
    MyObjectPtr p1; // Empty
    {
        MyObjectPtr p2(new MyObject());
        // There is now one "reference" to the created object
        p1=p2; // Copy the pointer.
        // There are now two references to the object.
    } // p2 is destroyed, leaving one reference to the object.
} // p1 is destroyed, leaving a reference count of zero.
  // The object is deleted.

Reference counted pointers are very useful when the lifetime of your object is much more complicated, and is not tied directly to a particular section of code or to another object.

There is one drawback to reference counted pointers — the possibility of creating a dangling reference:

// Create the smart pointer on the heap
MyObjectPtr* pp = new MyObjectPtr(new MyObject())
// Hmm, we forgot to destroy the smart pointer,
// because of that, the object is never destroyed!
Another possibility is creating circular references:

struct Owner {
   boost::shared_ptr<Owner> other;
};

boost::shared_ptr<Owner> p1 (new Owner());
boost::shared_ptr<Owner> p2 (new Owner());
p1->other = p2; // p1 references p2
p2->other = p1; // p2 references p1

// Oops, the reference count of of p1 and p2 never goes to zero!
// The objects are never destroyed!

To work around this problem, both Boost and C++11 have defined a weak_ptr to define a weak (uncounted) reference to a shared_ptr.

This answers is rather old, and so uses what was 'good' at the time, which was smart pointers provided by the boost library. Since C++11 the standard library has provided sufficient smart pointers types, and so you should favour the use of std::unique_ptr, std::shared_ptr and std::weak_ptr.

There is also std::auto_ptr. It is very much like a scoped pointer, except that it also has the "special" dangerous ability to be copied — which also unexpectedly transfers ownership! It is deprecated in the newest standards, so you shouldn't use it.

std::auto_ptr<MyObject> p1 (new MyObject());
std::auto_ptr<MyObject> p2 = p1; // Copy and transfer ownership.
                                 // p1 gets set to empty!
p2->DoSomething(); // Works.
p1->DoSomething(); // Oh oh. Hopefully raises some NULL pointer exception.

Should you be using something instead of what you should use instead?--Scott Meyers

The title is confusing, the article is not and should be read!

Should you be using something instead of what you should use instead?

by Scott Meyers

From the article:

The April 2000 C++ Report included an important article by Matt Austern: "Why You Shouldn't Use set—and What to Use Instead." It explained why lookup-heavy applications typically get better performance from applying binary search to a sorted std::vector than they'd get from the binary search tree implementation of a std::set. Austern reported that in a test he performed on a Pentium III using containers of a million doubles, a million lookups in a std::set took nearly twice as long as in a sorted std::vector...

Declaring the move constructor--Andrzej Krzemieński

An interesting question, with a proposed answer:

Declaring the move constructor

by Andrzej Krzemieński

From the article:

I am not satisfied with the solution I gave in the previous post. The proposed interface was this:


class Tool
{
private:
  ResourceA resA_;
  ResourceB resB_;
  // more resources
 
public:
  // Tools's interface
 
  Tool(Tool &&) = default;           // noexcept is deduced
  Tool& operator=(Tool&&) = default; // noexcept is deduced
 
  Tool(Tool const&) = delete;
  Tool& operator=(Tool const&) = delete;
};

static_assert(std::is_move_constructible<Tool>::value, "...");
static_assert(std::is_move_assignable<Tool>::value, "...");

In a way, it is self contradictory. The whole idea behind departing from the Rule of Zero is to separate the interface from the current implementation. Yet, as the comments indicate, the exception specification is deduced from the current implementation, and thus unstable...

A third way to use boost::serialization

The 10th installment in my series about writing applications with Qt and boost:

A third way to use boost::serialization

by Jens Weller

From the article:

The 10th part of my series about writing applications with Qt and boost is about using boost::serialization. The last part was about how to create the basic structure for a project with boost::filesystem, and how to use boost::filesystem to index folders. But there is a lot of data that just isn't able to be represented as single files, how to store it?

Originally I planned to use a database, as I already have some code handling the SQL queries nicely for me and most of my other applications currently also use this to store their data. Thats why most of my classes from the first day on had an id field, just to enable them to refer to an instance stored in a database. But then, if I could get around using a database, by simply just storing my data in a file, things would be easier, and my code wouldn't need to be scattered with SQL queries. If I couldn't find a reasonable approach, I still could opt for a database anyways.