What is a lambda expression in C++11?

The problem C++ includes useful generic functions like std::for_each and std::transform, which can be very handy. Unfortunately they can also be quite cumbersome to use, particularly if the functor you would like to apply is unique to the particular function. #include <algorithm> #include <vector> namespace { struct f { void operator()(int) { // do something … Read more

What is the difference between a definition and a declaration?

A declaration introduces an identifier and describes its type, be it a type, object, or function. A declaration is what the compiler needs to accept references to that identifier. These are declarations: extern int bar; extern int g(int, int); double f(int, double); // extern can be omitted for function declarations class foo; // no extern … Read more

Iterator invalidation rules for C++ containers

C++03 (Source: Iterator Invalidation Rules (C++03)) Insertion Sequence containers vector: all iterators and references before the point of insertion are unaffected, unless the new container size is greater than the previous capacity (in which case all iterators and references are invalidated) [23.2.4.3/1] deque: all iterators and references are invalidated, unless the inserted member is at … Read more

What is this weird colon-member (” : “) syntax in the constructor?

Foo(int num): bar(num) This construct is called a Member Initializer List in C++. Simply said, it initializes your member bar to a value num. What is the difference between Initializing and Assignment inside a constructor? Member Initialization: Foo(int num): bar(num) {}; Member Assignment: Foo(int num) { bar = num; } There is a significant difference … Read more

Why isn’t sizeof for a struct equal to the sum of sizeof of each member?

This is because of padding added to satisfy alignment constraints. Data structure alignment impacts both performance and correctness of programs: Mis-aligned access might be a hard error (often SIGBUS). Mis-aligned access might be a soft error. Either corrected in hardware, for a modest performance-degradation. Or corrected by emulation in software, for a severe performance-degradation. In … Read more

What are copy elision and return value optimization?

Introduction For a technical overview – skip to this answer. For common cases where copy elision occurs – skip to this answer. Copy elision is an optimization implemented by most compilers to prevent extra (potentially expensive) copies in certain situations. It makes returning by value or pass-by-value feasible in practice (restrictions apply). It’s the only … Read more