Enrico Zini: cxx11-talk-notes
C++11 talk notes
On 2014-11-27 I gave a talk about C++ and new features introduced with C++11:
these are the talk notes. See cxx11-talk-examples for the examples.
(note: I had to add
See also
this for more nice
examples. See
this
and
this
for further discussion.
Multiline strings
See this.
C++ memory management protip
RAII: Resource Acquisition Is Instantiation
This is not new in C++11, but in my experience I have rarely seen it mentioned
in C++ learning material, and it does make a huge difference in my code.
See this
and this for
details.
Constructors and member initializer lists
Initializers in curly braces now have their own type:
See this for
details, including the new uniform initialization trick of omitting parentesis
in constructors so that you can call normal constructors and
See
this
for more details.
Range-based for loop
C++ now has an equivalent of the various foreach constructs found in several
interpreted languages!
See this and
this
for details.
Lambda functions and expressions
Lambdas! Closures!
Something like this:
Becomes this:
And something like this:
Becomes this:
See this,
this
and this.
Tuple types
C++ now has a
See here,
here and
here.
Regular expressions
We now have regular expressions!
The syntax is ECMAScript by default and can be optionally changed to basic,
extended, awk, grep, or egrep.
See here and
here.
General-purpose smart pointers
There is
See here
and here.
Miscellaneous other cool things
Standard attribute specifiers
See here.
Hash tables
See here and look at the
new containers
See here and
here.
Essential tools
You need at least g++ 4.8 or
clang 3.3 to have full C++11 support.
They will be both available in jessie, and for wheezy you can use the nightly
clang packages repository. I cannot think of a good
excuse not to use
U+2063 INVISIBLE SEPARATOR to prevent noreturn
statements to be misinterpreted by the blog formatter. If you copypaste the
code and encounter issues, you may want to delete the noreturn statements and
retype them)
Overview of programming languages
It has to be as fast as possible, so interpreted languages are out. You don't want to micro manage memory, so C is out. You don't want to require programmers to have a degree, so C++ is out. You want fast startup and not depend on a big runtime, so Java is out. [...] (Bram Moolenaar)C++ secret cultist protip
Do not call up what you cannot put down.C++ is a compiled language It is now possible to use the keyword
constexpr to mark functions and objects
that can be used at compile time:
/*
* constexpr tells the compiler that a variable or function can be evaluated at
* compile time.
*
* constexpr functions can also be run at run time, if they are called with
* values not known at compile time.
*
* See http://en.cppreference.com/w/cpp/language/constexpr for more nice examples
*
* It can be used to avoid using constants in code, and using instead functions
* for computing hardware bitfields or physical values, without losing in
* efficiency.
*/
#include <iostream>
using namespace std;
constexpr int factorial(int n)
return n <= 1 ? 1 : (n * factorial(n-1));
int main()
cout << "Compile time factorial of 6: " << factorial(6) << endl;
cout << "Enter a number: ";
int a;
cin >> a;
cout << "Run time factorial of " << a << ": " << factorial(a) << endl;
const char* code = R"--(
printf("foo\tbar\n");
return 0;
)--";
std::initializer_list:
#include <string>
#include <iostream>
#include <unordered_set>
using namespace std;
// std::initializer_list< >
// will have as its value all the elements inside the curly braces
string join(initializer_list<string> strings)
string res;
for (auto str: strings)
if (!res.empty())
res += ", ";
res += str;
return res;
int main()
unordered_set<string> blacklist ".", "..", ".git", ".gitignore" ;
cout << join( "antani", "blinda" ) << endl;
initializer_list
constructors with the same syntax, which looks like an interesting thing when
writing generic code in templates.
Type inference
I can now use auto instead of a type to let the compiler automatically
compute the value of something I assign to:
auto i = 3 + 2;
// See also https://github.com/esseks/monicelli
vector<string> names "antani", "blinda", "supercazzola" ;
for (auto i = names.cbegin(); i != names.cend(); ++i)
cout << i;
template<typename T>
T frobble(const T& stuff)
// This will work whatever type is returned by stuff.read()
auto i = stuff.read();
//
for (auto i: list_of_stuff)
cout << i << endl;
for (auto n: 0,1,2,3,4,5 )
cout << n << endl;
// This construct:
for (auto i: stuff)
// If stuff is an array, it becomes:
for (i = stuff, i < stuff + sizeof(stuff) / sizeof(stuff[0]); ++i)
// If stuff has .begin() and .end() methods it becomes:
for (i = stuff.begin(); i != stuff.end(); ++i)
// Otherwise it becomes:
for (i = begin(stuff); i != end(stuff); ++i)
// And you can define begin() and end() functions for any type you
// want, at any time
// JavaScript
var add = function(a, b) return a + b;
# Python
add = lambda a, b: a + b
auto add = [](int a, int b) return a + b;
// JavaScript
var a = 0;
$.each([1, 2, 3, 4], function(idx, el) a += el );
unsigned a = 0;
std::for_each( 1, 2, 3, 4 , [&a](int el) return a += el; );
std::tuple type, that like in Python can be used to implement
functions that return multiple values:
tuple<int, string, vector<string>> parse_stuff()
return make_tuple(id, name, values);
string name; vector<string> values;
// std::ignore can be used to throw away a result
tie(ignore, name, values) = parse_stuff();
// std::tie can also be used to do other kind of
// multi-operations besides assignment:
return tie(a, b, c) < tie(a1, b1, c1);
// Is the same as:
if (a != a1) return a < a1;
if (b != b1) return b < b1;
return c < c1;
std::regex re(R"((\w+)\s+(\w+))");
string s("antani blinda");
smatch res;
if (regex_match(s, res, re))
cout << "OK " << res[1] << " -- " << res[2] << endl;
std::unique_ptr to code memory ownership explicitly, and
std::shared_ptr as a reference counted pointer, and smart pointers can have
custom destructors:
unique_ptr<dirent, std::function<void(void*)>> dirbuf((dirent*)malloc(len), free);
string errno_str(int error)
char buf[256];
#if (_POSIX_C_SOURCE >= 200112L _XOPEN_SOURCE >= 600) && ! _GNU_SOURCE
strerror_r(errno, buf, 256);
string res(buf);
#else
string res(strerror_r(errno, buf, 256));
#endif
return res;
[ [noreturn]] void throw_libc_error(int error)
throw runtime_error(errno_str(error));
unordered_set,
unordered_map,
unordered_multiset, and
unordered_multimap.
Multithreading
There is a standard threading model, with quite a bit of library support: see
here,
here,
here, and here
for atomic data structures.
Variadic templates
Templates can now take variable number of arguments, and that opens
possibilities for interesting code generation, like implementing a generic,
type-safe printf statement, or something like this:
db.query(R"(
INSERT INTO table NAMES (id, name, description)
VALUES (?, ?, ?)
)", 4, "genio", "fantasia, intuizione, decisione, e velocit di esecuzione");
-Wall on new code.
scan-build from clang is
another nice resource for catching even more potential problems at compile
time.
valgrind is a great tool for runtime code analysis:
valgrind --tool=memcheck (the default) will check your program for wrong
memory accesses and memory leaks. valgrind --tool=callgrind will trace
function calls for profiling, to be analyzed with
kcachegrind. valgrind
--tool=helgrind can check multi-threaded programs for suspicious concurrent
memory accesse patterns.
And of course
gdb: a nice
trick with C++ is to issue catch throw to get a breakpoint at the point
where an exception is being thrown. help catch provides a list of other
interesting catch examples.
Coredump tips: ulimit -c to enable core dumps, triggering a core dump with
^\, opening a core with gdb program core, and more details on man 5 core.
An extra gdb tip, which is not related to C++ but helped me considerably
recently, is that it can be attached to running python programs to get a live
Python traceback.
The
and gives a preview of the wide range of commercial opportunities that WebRTC is creating for software vendors to displace traditional telecommunications providers.
xTupleCon also gave me a great opportunity to see new features (like the
With
Big changes are always a complicated thing to get done and can be the harder the bigger or more diverse an organization is it is taking place in.
Transparency
Ideally every change is well communicated early and openly.
Leaving people in the dark about what will change and when means people have much less time to feeling comfortable about it or arranging with it mentally.
Especially bad can be extending the change later or or shortening transition periods.
Letting people think they have some time to transition only to force them to rush later will remove any credibility you have and severely reduce their ability to believe you are not crossing them.
Making a new way optional is a great way to create security (see below), but making that obligatory before the change even arrives as optional with them will not make them very willing to embrace change.
Take responsibility
Every transformation means costs.
Even if some change did only improve and did not make anything worse once implemented (the ideal change you will never meet in reality), the deployment of the change still costs:
processes have adapted to it, people have to relearn how to do things, how to detect if something goes wrong, how to fix it, documentation has to be adopted and and and.
Even as the change causes more good than costs in the whole organization (let's hope it does, I hope you wouldn't try to do something if the total benefit is negative), the benefits and thus the benefit to cost ratio will differ for the different parts of your organization or the different people within it.
It's hardly avoidable that for some people there will not be much benefit, much less perceived benefit compared to the costs they have to burden for it.
Those are the people whose good will you want to fight for, not the people you want to fight against.
They have to pay with their labor/resources and thus their good will for your benefit the overall benefit.
This is much easier if you acknowledge that fact.
If you blame them for having the costs, claim their situation does not even exist or even ridicule them for not embracing change you only prepare yourself for frustration.
You might be able to persuade yourself that everyone that is not willing to invest in the change is just acting out of malevolent self-interest.
But you will hardly be able to persuade people that it is evil to not help your cause if you treat them as enemies.
And once you ignored or played down costs that later actually happen, your credibility in being able to see the big picture will simply cease to exist at all for the next change.
Allow different metrics
People have different opinions about priorities, about what is important, about how much something costs and even about what is a problem.
If you want to persuade them, try to take that into account.
If you do not understand why something is a reason, it might be because the given point is stupid. But it might also be that you miss something. And often there is simple a different valuation of what is important, what the costs are and what are problems.
If you want to persuade people, it is worth to try to understand those.
If all you want to do is persuade some leader or some majority then ridiculing their concerns might get you somewhere.
But how do you want to win people over if you do not even appear to understand their problems.
Why should people trust you that their costs will be worth the overall benefits if you tell them the costs that they clearly see do not exist? How credible is referring to the bigger picture if the part of the picture they can see does not match what you say the bigger picture looks like?
Don't get trolled and don't troll
There will always be people that might be unreasonable or even try to provoke you. Don't allow being provoked. Remember that for successful changes you need to win broad support. Feeling personally attacked or feeling presented a large amount of pointless arguments easily results in not bringing proper responses or actually looking at arguments.
If someone is only trolling and purely malevolent, they will tease you best if they bring actual concerns of people in a way you likely degrade your yourself and your point in answering.
Becoming impertinent with the troll is like attacking the annoying little goblin hiding next to the city guards with area damage.
When not being able to persuade people, it is also far to easy to consider them in bad faith and/or attacking them personally. This can only escalate even more. Worst case you frustrate someone in good faith. In most cases you poison the discussion so much that people actually in good faith will no longer contribute the discussion. It might be rewarding short term because after some escalation only obviously unreasonable people will talk against you, but it makes it much harder to find solutions together that could benefit anyone and almost impossible to persuade those that simply left the discussion.
Give security
Last but not least, remember that humans are quite risk-averse. In general they might invest in (even small) chances to win, but go a long way to avoid risks.
Thus an important part of enabling change is to reduce risks, real and perceived ones and give people a feeling of security.
In the end, almost every measure boils down to that:
You give people security by giving them the feeling that the whole picture is considered in decisions (by bringing them early into the process, by making sure their concerns are understood and part of the global profit/cost calculation and making sure their experiences with the change are part of the evaluation).
You give people security by allowing them to predict and control things (by transparency about plans, how far the change will go and guaranteed transitions periods, by giving them enough time so they can actually plan and do the transition).
You give people security by avoiding early points of no return (by having wide enough tests, rollback scenarios,...).
You give people security by not letting them alone (by having good documentation, availability of training, ...).
Especially side-by-side availability of old and new is an extremely powerful tool, as it fits all of the above:
It allows people to actually test it (and not some little prototype mostly but not quite totally unrelated to reality) so their feedback can be heard. It makes it more predictable as all the new ways can be tried before the old ones no longer work. It is the ultimate role-back scenario (just switch off the new). And allows for learning the new before losing the old.
Of course giving the people a feeling of security needs resources. But it is a very powerful way to get people to embrace the chance.
Also in my experience people only fearing for themselves will usually mostly be passive by not pushing forward and trying to avoid or escape the changes.
(After all, working against something costs energy, so purely egoistic behavior is quite limiting in that regard).
Most people actively pushing back do it because they fear for something larger than only them. And any measure to making them fear less that you ruin the overall organization, not only avoids unnecessary hurdles rolling out the change but also has some small chance to actually avoid running into disaster with closed eyes.













Wednesday 1:
If you have users behind NAT, you ll also need a TURN server for relay:
In both cases, setup is not too difficult, particularly if using
Last Wednesday I had the pleasure and honor to have a great guest again at my class:
It started with OPW
The key point to emphasize is that Juliana's work in GSoC was actually made possible by Debian's decision to participate in and promote Outreach Program for Women in 2013.
I've previously attended DebConf myself to help more developers become familiar with free and open RTC technology. I wasn't able to get there this year but thanks to the way GSoC and OPW are expanding our community, Juliana was there to help out.

