Tag Archive for C++11

Book “C++ Lambda Story”

A friend of mine published a new book, titled “C++ Lambda Story”. The book explains everything you need to know about lambda expressions in C++.

The book guides you through the evolution of C++ Lambda Expressions so that you can learn it step by step. It starts with C++03 and a motivation to have “ad-hoc” functors, and then moves into the latest C++ standards:

  • C++11 – early days of the feature. You’ll learn about all the essential aspects of lambdas and several tricks you might apply. This is the longest chapter as it needs to cover a lot of topics.
  • C++14 – updates. See how to use generic lambdas and captures with an initializer.
  • C++17 – more improvements, especially by handling ‘this’ pointer and allowing ‘constexpr’. You’ll also learn about the overloaded pattern and how to derive from lambda.
  • C++20 – in this section you’ll see all of the new features adopted for C++20 like template lambdas and how to use them with concepts and constexpr algorithms.

Additionally, throughout the chapters, you’ll learn about the following techniques:

  • Immediately Invoked Functional Expressions (IIFE)
  • How to instrument a default functor to gather extra information
  • Replacing std::bind1st, std::bind2nd and removed functional stuff
  • The Overloaded Pattern and how to inherit from a lambda
  • Passing C++ captureless lambda as a function pointer to C API
  • LIFTING with lambdas
  • Storing lambdas in a container
  • Variadic templates and arguments packs
  • Lambdas and asynchronous execution
  • and many more

The author, Bartłomiej Filipek, is giving a 28% discount to readers of my blog. This offer is valid until 27th of January 2021.
Follow this link to use the coupon if you are interested in this offer.

Share

Implementing a Thread-Safe Singleton with C++11 Using Magic Statics

A couple of years ago I wrote a blogpost on how to write a thread-safe singleton using C++11. That implementation used std::call_once().

However, if your compiler is fully C++11 compliant, and by now, all major compilers are fully compliant, then the best way to implement a singleton is to use a magic static, as follows:

class CSingleton final
{
public:
	static CSingleton& GetInstance();

private:
	CSingleton() = default;
	~CSingleton() = default;

	CSingleton(const CSingleton&) = delete;
	CSingleton& operator=(const CSingleton&) = delete;
	CSingleton(CSingleton&&) = delete;
	CSingleton& operator=(CSingleton&&) = delete;
};

CSingleton& CSingleton::GetInstance()
{
	static CSingleton instance;
	return instance;
}

The most important change is the implementation of GetInstance() which now contains a local static variable (magic static). C++11 guarantees that this will be initialized in a thread-safe way.
I have now also marked the class as final, made the destructor non-virtual and private, and deleted the move constructor and move assignment operator.

Share

Milestone: VS 2015 Update 2’s Standard Library is C++11, C++14, and C++17-so-far Feature Complete

The C++ Standard Library in the Visual Studio 2015 Update 2 release is C++11, C++14, and C++17-so-far feature complete. This includes all features from C++17 that are currently in that standard proposal: SFINAE-friendly result_of, improvements to pair and tuple, shared_mutex, removal of deprecated iostreams aliases, variable templates for type traits (is_same_v, …), as_const(), logical operator type traits (conjunction, …), owner_less<>, variadic lock_guard, and additions to <chrono>: floor(), ceil(), round(), and abs().
More information, including a detailed list can be found here.

Share

Modern C++ Tips and Tools

C++ allows you to write clean, safe and fast code, and writing it is even easier than ever thanks to new features in C++11 and C++14. This article highlights a couple of tips.

Comments & ‘Cleverness’

Code gets read a lot more often than it gets written, so make sure that your code can be read and understood in the future, by yourself and by other developers. This means that you have to add comments, and that you should avoid trying to make code as terse and ‘clever’ as possible; because that hurts readability.

Memory Management

In modern C++ you should avoid any explicit calls to delete operators or functions to deallocate memory such as free(). Code that relies on such explicit calls is susceptible to memory leaks. For example:

void foo(size_t size) {
    char* buffer = new char[size];
    // ...
    delete [] buffer;
}

The code is straightforward; it allocates memory, does something with the memory, and then deletes the memory. It uses a ‘naked’ pointer, which you have to manage yourself. This piece of code causes a memory leak if an exception is thrown before the delete operator is called. You should avoid using naked pointers, instead use encapsulation objects that automatically handle the memory. For example, the above code should be written using a container such as a vector:

void foo(size_t size) {
    std::vector buffer(size);
    // ...
}

Using a container, there is no need to free the memory, the destructor of the container will handle all that for you. Similarly, if you need dynamically allocated objects, do not store them in naked pointers, instead use smart pointers such as std::unique_ptr, which is not reference counted, or if you need shared ownership, std::shared_ptr, which is reference counted. unique_ptr will automatically delete the object when the unique_ptr goes out of scope. An object wrapped in a shared_ptr is automatically deleted when the reference count goes to zero.

When you use unique_ptr, use std::make_unique<>(). Similarly, use std::make_shared<>() when you use shared_ptr.

One key point to remember: never use std::auto_ptr, it has officially been deprecated because of its problems. One of its problems is that it is forbidden to store them in STL containers because auto_ptr does not meet C++98/03’s requirements for container elements.  unique_ptr  and shared_ptr don’t have any of these problems and are perfectly safe to use in STL containers.

The auto Keyword

Use auto to let the compiler deduce the type of variables automatically. This helps a lot with complicated types that are hard or even impossible to write. For example:

std::map<std::string, std::vector> myMap;
for (std::map<std::string, std::vector>::iterator iter = begin(myMap);
     iter != end(myMap); ++iter)
{
    //...
}

This is complicated, difficult to write and error prone.
Note that since C++11 it’s recommended to use the non-member functions std::begin(), end(), cbegin(), cend(), rbegin(), rend(), crbegin(), and crend() instead of the member functions.
Using the auto keyword the above can be rewritten in a very clean way:

for (auto iter = begin(myMap); iter != end(myMap); ++iter) { ... }

Using the range-based for loop, the code can be written even more elegantly:

for (auto&& item : myMap) { ... }

Or:

for (auto& item : myMap) { ... }

Or:

for (const auto& item : myMap) { ... }

Never write the following, unless your container only contains primitive types:

for (auto item : myMap) { ... }

If you use this for containers with non-primitive elements performance will suffer because item will be a copy of each of the elements in the container.

nullptr

Do not use NULL for pointers, use the nullptr keyword. NULL is a macro for 0 which can sometimes result in problems that are hard to track down. nullptr is really a null pointer type and is not just a macro for 0.

Move Semantics

Move semantics since C++11 helps with performance, allowing objects to be moved instead of copied. It is based on rvalue references, represented as &&. C++ automatically uses move semantics in cases where the source object will cease to exist. You can explicitly move an object by using std::move(). The STL also supports move semantics. To add move semantics to your classes you only need to implement a move constructor and move assignment operator which have the following prototype:

MyObject(MyObject&& src);               // Move constructor
MyObject& operator=(MyObject&& rhs);    // Move assignment operator

Lambda Expressions

Lambda expressions are a powerful addition to the C++ language. One huge benefit is that they make it much easier to use STL algorithms. For example, you can use the count_if() algorithm in combination with a simple lambda expression to count all elements in a vector that are less than 0.

std::vector vec;
auto count = std::count_if(cbegin(vec), cend(vec),
    [](int i){ return i < 0; });

Investing time in learning about lambda expressions will pay itself off quickly.

Threading

You should read up on the threading functionalities introduced in C++11. One useful and often overlooked function is std::call_once(), used to make sure that a specific callable entity is executed exactly one time, no matter how many threads call it simultaneously. This can for example be used to make a compact and thread safe implementation of the singleton pattern.

Strings

Text matching, parsing, and searching can be tricky and complicated, especially when it should work with Unicode strings. You should avoid writing your own functions to perform such operations, instead use classes from <regex> such as std::wregex.

C++11 supports raw string literals. They are extremely useful in the context of regular expressions. For example, the following regular expression searches for spaces, newlines, and backslashes:

string s = "( |\\n|\\\\)";

The last 4 backslashes are correct. If you want to match a backslash, it needs to be escaped in the regular expression, thus \\. If you want to write \\ in a normal string literal, you need to escape both backslashes, resulting in 4 of them. Using raw string literals you simply write:

string s = R"(( |\n|\\))";

R”( and )” denote the boundary of the raw string literal.

Random Numbers

If your application needs to generate random numbers, don’t use the old C style srand()/rand() functions. Their randomness is not good. Instead, use <random>, which contains classes to generate random numbers, such as a Mersenne Twister, and supports different mathematical distributions, for example a uniform distribution, a Poisson distribution, and so on.

Further Reading

Take a look at “Professional C++ 2nd Edition” if you are determined to master C++, including all C++11 features.

Share

My Article “Advanced C++ Tips and Tools” on Amazon

My article “Advanced C++ Tips and Tools” is live on the tech.book(store) website of Amazon.

C++ allows you to write clean, safe and fast code, and writing it is even easier than ever thanks to new features in C++11. This article highlights a couple of tips…

You can read the full article here.

Share

Visual C++ November CTP, now with more C++11

As promised, Microsoft is releasing out-of-band updates for Visual C++. A preview of the first such update has now been released as the November 2012 Compiler CTP. This is a Customer Technology Preview and does not come with a ‘Go Live’ license, but it allows you to start experimenting and testing new features, and to provide feedback.

This November 2012 CTP contains a lot of new C++11 features:

  • Variadic templates
  • Uniform initialization and initializer_lists
  • Delegating constructors
  • Raw string literals
  • Explicit conversion operators
  • Default template arguments for function templates

More details, including installation instructions and how to give feedback can be found here.

Download the November 2012 CTP and start playing with these new C++11 features.

Share

The Future of C++

Herb Sutter’s talk about The Future of C++ is now available on Channel9. If you are interested in C++, you should watch it. A the same time, he announced a couple of major things related to C++:

Interest and investment in C++ continues to accelerate across the software world.

  • ISO C++ standardization is accelerating. Major companies are dedicating more people and resources to C++ standardization than they have in years. Over the next 24 months, the plan is to ship three Technical Specifications and a new C++ International Standard.
  • C++ now has a home on the web at isocpp.org. It both aggregates the best C++ content and hosts new content itself, including Bjarne Stroustrup’s new Tour of C++ and Scott Meyers’ new Universal References article.
  • There is now a Standard C++ Foundation. It is already funded by the largest companies in the industry down to startups, financial institutions to universities, book publishers to other consortia, with more members joining weekly. For the first time in C++’s history since AT&T relinquished control of the language, we have an entity – a trade organization – that exists exclusively to promote Standard C++ on all compilers and platforms, and companies are funding it because the world runs on C++, and investing in Standard C++ is good business.

This is an exciting time to be in the C++ World 🙂

Share

Implementing a Thread-safe Singleton with C++11

Note: see my more recent article “Implementing a Thread-Safe Singleton with C++11 Using Magic Statics” for a more modern solution.

C++11 makes it easier to write a thread-safe singleton. Here is an example. The class definition of the singleton looks as follows:

#include <memory>
#include <mutex>

class CSingleton
{
public:
	virtual ~CSingleton() = default;
	static CSingleton& GetInstance();

private:
	static std::unique_ptr<CSingleton> m_instance;
	static std::once_flag m_onceFlag;
	CSingleton() = default;
	CSingleton(const CSingleton& src) = delete;
	CSingleton& operator=(const CSingleton& rhs) = delete;
};

The implementation of the GetInstance() method is very easy using C++11 std::call_once() and a lambda:

std::unique_ptr<CSingleton> CSingleton::m_instance;
std::once_flag CSingleton::m_onceFlag;

CSingleton& CSingleton::GetInstance()
{
	std::call_once(m_onceFlag,
		[] {
			m_instance.reset(new CSingleton);
	});
	return *m_instance.get();
}
Share

GoingNative 2012 Content Available

GoingNative 2012 was a 48 hour, globally live-streamed technical event for those who push the boundaries of general purpose computing by exploiting the true capabilities of the underlying machine: C++ developers. Distinguished speakers included the creator of C++, Bjarne Stroustrup, C++ Standards Committee Chair, Herb Sutter, C++ template and big compute master, Andrei Alexandrescu, STL master Stephan T. Lavavej, LLVM/Clang developer Chandler Carruth, distributed and parallel computing expert Hans Boehm, and C++ library design expert and ISO committee member Andrew Sutton.

“C++11 feels like a new language” says C++ creator Bjarne Stroustrup, who presented the keynote at the event.

You can watch the entire GoingNative 2012 streaming video from here.

Below is a list of all individual sessions. Downloads of each individual session will come online in the coming days. These sessions are a must-see for C++ developers.

Day 1 – C++11 Today (Feb 2, 2012)

Day 2 – C++11 Today and Tomorrow (Feb 3, 2012)

Share

Slides of Presentation “C++11 (C++0x) in Visual C++ 2010”

A couple of months ago, I gave a presentation about C++11/C++0x features supported in Visual C++ 2010 for software engineers at my company. You can now download the slides.

Share

C++11 Standard Published by ISO

The ISO International Organization for Standardization has now officialy published the C++11 standard 🙂
Here is part of the press release:

C++, one of the most popular programming languages used in everything from Web browsers to 3D video games, has been fully updated and published as, ISO/IEC 14882:2011, Information technology – Programming languages – C++.

ISO/IEC 14882:2011 defines the programming language and specifies requirements for implementation. Also known as C++11, this is the first major revision of the standard since 1998. Its new features extend C++’s traditional strengths of flexibility and efficiency – for example, lambda functions, move semantics, and variadic templates further enable developers to use powerful expressiveness and strong abstraction to write efficient, high-performance code with full access to the hardware available when needed. Even more, the new C++11 has the convenience and ease of use of other modern languages – from features like auto type deduction and explicit virtual override control, to standard smart pointers that mean never writing delete again.

You can read the complete press release here.

Share

“Professional C++, Second Edition” Featured on the Microsoft VC++ Team Blog

My book “Professional C++, Second Edition”, published by Wiley/Wrox, is now featured in a dedicated post on the Microsoft Visual C++ Team Blog 🙂
Read the VC++ Team Blog post here.

Share

C++11 Now the Confirmed Name

Yesterday, I wrote a post about the fact that C++0x was unanimously approved.
Today, we got confirmation from Geneva that they will officially publish the new C++ standard in a matter of weeks with the name “ISO/IEC 14882:2011(E) Programming Languages — C++, Third Edition“, which means we can start calling it C++11

See also Herb Sutter’s update on his blog.

Now I can finalize the last pieces for my “Professional C++, Second Edition” book (Wiley/Wrox).

This is a great day for the C++ world! 🙂

Share

C++0x Unanimously Approved

The new C++ standard has been unanimously approved and is now an international standard.
It can still take a few months before it’s officially published, so the question still remains whether it will be called C++11 or C++12. I for sure hope it will be C++11 🙂
Here is Herb Sutter’s blog post about it.

Share