Difference in make_shared and normal shared_ptr in C++

The difference is that std::make_shared performs one heap-allocation, whereas calling the std::shared_ptr constructor performs two. Where do the heap-allocations happen? std::shared_ptr manages two entities: the control block (stores meta data such as ref-counts, type-erased deleter, etc) the object being managed std::make_shared performs a single heap-allocation accounting for the space necessary for both the control block and the data. In the other … Read more

How do I activate C++ 11 in CMake?

As it turns out, SET(CMAKE_CXX_FLAGS “-std=c++0x”) does activate many C++11 features. The reason it did not work was that the statement looked like this: Following this approach, somehow the -std=c++0x flag was overwritten and it did not work. Setting the flags one by one or using a list method is working.

Correct way of looping through C++ arrays

In C/C++ sizeof. always gives the number of bytes in the entire object, and arrays are treated as one object. Note: sizeof a pointer–to the first element of an array or to a single object–gives the size of the pointer, not the object(s) pointed to. Either way, sizeof does not give the number of elements in the array (its length). To get the … Read more

How does std::forward work? [duplicate]

First, let’s take a look at what std::forward does according to the standard: ยง20.2.3 [forward] p2 Returns: static_cast<T&&>(t) (Where T is the explicitly specified template parameter and t is the passed argument.) Now remember the reference collapsing rules: (Shamelessly stolen from this answer.) And then let’s take a look at a class that wants to employ perfect forwarding: And now an example invocation: … Read more

Thread pooling in C++11

This is copied from my answer to another very similar post: Start with maximum number of threads the system can support:int num_threads = std::thread::hardware_concurrency(); For an efficient threadpool implementation, once threads are created according to num_threads, it’s better not to create new ones, or destroy old ones (by joining). There will be a performance penalty, an … Read more

What is move semantics?

I find it easiest to understand move semantics with example code. Let’s start with a very simple string class which only holds a pointer to a heap-allocated block of memory: Since we chose to manage the memory ourselves, we need to follow the rule of three. I am going to defer writing the assignment operator and … Read more