basics

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: 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...

Is C++11 uniform initialization a replacement for the old style syntax? -- Programmers.StackExchange

Here is a question from Programmer's StackExchange (tags [c++] and [c++11]) which most C++ developers, whatever their level, will ask as soon as they are introduced to the new Uniform Initialization syntax:

Is it recommended now to use uniform initialization in all cases? What should the general approach be for this new feature as far as coding style goes and general usage? What are some reasons to not use it?

The accepted answer clearly provides very good reasons to use this new syntax as much as possible (if your compiler supports it already): minimizing redundant typenames and avoiding the Most Vexing Parse. It also points some reasons to not use this syntax, in particular in case you're trying to call a standard container constructor.

There is one other reason not to:

std::vector<int> v{100};

What does this do? It could create a vector<int> with one hundred default-constructed items. Or it could create a vector<int> with one item whose value is 100. ... In actuality, it does the latter.

Read the full QA.

Read Stroustrup's FAQ about Uniform Initialization syntax.

Bjarne Stroustrup interview: From the Foundation and C++11, to portability and the C++ resurgence

Last Monday, Bjarne Stroustrup gave a live interview to David Intersimone of Embarcadero to kick off their CodeRage 7 conference. Bjarne discusss the new Standard C++ Foundation, the ISO C++11 standard, new language features, how C++11 builds on C++’s strengths, application portability, and C++’s ubiquitous presence in the markets.

The video is now on YouTube. Enjoy.

 

Quick Q: Why does std::map not have a const accessor? -- StackOverflow

To help balance out "introductory," "intermediate," and "advanced" content, we're trying an experiment to highlight interesting bite-sized tidbits that are in the first two categories.

Here's today's tidbit from StackOverflow's [c++11] tag:

The declaration for the [] operator on a std::map is this:

T& operator[] ( const key_type& x );

Is there a reason it isn't this?

T& operator[] ( const key_type& x );

const T& operator[] const ( const key_type& x );

Because that would be incredibly useful any time you need to access a member map in a const method.

As the two top answers show, the answer is different in C++98 and C++11, and C++11 is where it's "at" (pardon).

Read answers on StackOverflow...

Tour of C++: Second chapter posted

This 2nd chapter of my Tour of C++ introduces the basic C++ abstraction mechanisms. If you have a 1990s view of C++, you are in for a few surprises: the integrated set of abstraction mechanisms in C++11 allows for simpler and more powerful abstractions than previously. For starters, pointers basically disappear from sight (hiding inside resource handles). Naturally, this is achieved without loss of performance. Enjoy!

Constructive comments would be most welcome.

C++11 Style: A Touch of Class -- Bjarne Stroustrup

C++11 Style: A Touch of Class -- Bjarne Stroustrup

How do we write good code in idiomatic C++11? What principles, techniques, and idioms can we exploit to make it easier to produce quality code? In this presentation, I make an argument for type-rich interfaces, compact data structures, integrated resource management and error handling, and highly-structured algorithmic code. I illustrate my ideas and guidelines with a few idiomatic code examples.

I use C++11 freely. Examples include auto, general constant expressions, uniform initialization, type aliases, type safe threading, and user-defined literals. This presentation reflects my thoughts on what "Modern C++" should mean in the 2010s: a language for programming based on light-weight abstraction with direct and efficient mapping to hardware, suitable for infrastructure code.

C++ Rvalue References Explained--Thomas Becker

What are rvalue references and move semantics, and how do they work again, exactly?

If you haven't read Thomas Becker's nice explanation (or even if you have), be sure to check it out:

C++ Rvalue References Explained

Thomas Becker

1. Introduction
2. Move Semantics
3. Rvalue References
4. Forcing Move Semantics
5. Is an Rvalue Reference an Rvalue?
6. Move Semantics and Compiler Optimizations
7. Perfect Forwarding: The Problem
8. Perfect Forwarding: The Solution
9. Rvalue References and Exceptions
10. The Case of the Implicit Move
11. Acknowledgments and Further Reading