Scrupulous Abstractions

Spare time experimentation with C++11



This is the index page.

Have a look at the list of post to the right, or go to the first post.

Commenting is enabled on each blog post,
go to any of the individual posts.


C++11: type-safe use of integer user defined literals. -123_foo

C++11 provides a new way of specifying literal constants, called user defined literals. It allows you to define your own markers (for example for units), such as  _kilograms, _meters, or _steps, in addition to the built-in ones, like U or ULL for unsigned and unsigned long long.

Once you have defined the literal, you can use it anywhere where where you need a constant, such as:

auto stepsA = 7_steps;
cout << 21_steps << end;

There is no direct support for signed literals. What I mean by that is that an expressions such as

auto MySteps=-55_steps; 

is going to be interpreted as

auto MySteps=-(55_steps);

and only the literal 55 is available for parsing. The simplest way do declare and define a _steps literal that attaches to integers are by using the following signature:

int operator"" _steps(unsigned long long value){
  return value;
}

The unsigned long long is mandatory here: That means that just taking value as int or, say, long long, is not supported by the C++ standard. Now we quickly arrive at the problem I faced. Let’s try:

cout << 55_steps<< endl;
cout << -55_steps << endl;

That works fine, but what about

cout << 4294967299_steps ;

That value is 3 too big to be stored in a signed integer (on my system), so I get a 3 printed instead of 4294967299, due to integer overflow. And - the compiler did not even warn about this!

The motivation for using user-defined literals is mainly type safety, so how can we obtain a definition of _steps that is protected at compile time against this and similar problems?

Narrowing conversions and brace-initiaization

C++11 has a new syntax called brace-initialization. Among other things, it has the property that so called narrowing conversions (such as the one from unsigned long to int) is not permitted. For example, if we write

int i{4294967299};

the compiler is required to give a diagnostic (warning or error). With gcc we can turn the error on by using the option -Werror-narrowing. That seems like the right thing, but by itself id does not help. We can’t just write

int operator"" _steps(unsigned long long value){
  return {value};
}

…because the parameter value is always going to be of type unsigned long long even if the actual passed number is small, so -Werror-narrowing will always be triggered. We need a way to define the _steps operator such that value is replaced, during compilation, with the actual passed number.

constexpr is not enough…

For doing work during compilation we first of all declare the operator as a constant expression by using the ‘constexpr’ specifier. Using constexpr, we can almost get what we want. We can still not use {value} because the type of value is always unsigned long long, but we can do some checks ourselves, like this:

#include <limits>
#include <stdexcept>
constexpr int operator"" _steps(unsigned long long value){
  return (numeric_limits<int>::max()>=value) ? value : throw std::exception() ;
}

This works fine and will prevent compilation of cases such as this:

constexpr auto x= 4294967299_steps;
cout << x <<endl;

By the way, exceptions are allowed to be used like we did above. The compilation error generated (we asked for it) is:

in constexpr expansion of 'operator"" _steps(4294967299ull)'
error: expression '<throw-expression>' is not a constant-expression

.. But we are not done! constexpr functions can be called either at compilation or during program execution, and in fact, the following two cases do compile:

cout << 4294967299_steps <<endl;
auto x= 4294967299_steps ;
cout << x <<endl;

This is exactly what we wanted to forbid. Instead of a compiler error we get exceptions when running the code. I need a solution where I can be sure that if the program compiles, all constants are type-safe.

constexpr and a bit of template meta-programming

To force the constexpr function to be evaluated we have to use the template form of user defined literals. This is a bit more complicated, but not too bad, and it does exactly what we want. This is how the solution looks from the use point of view:

template<char... Chars>
int operator"" _steps(){
return {litparser<0,Chars...>::value};
}

Litparser is a little template meta-program which takes a list of characters as arguments expanded from the input characters held by the Chars parameter pack.

typedef unsigned long long ULL;

// Delcare the litparser
template<ULL Sum, char... Chars> struct litparser;

// Specialize on the case where there's at least one character left:
template<ULL Sum, char Head, char... Rest>
struct litparser<Sum, Head, Rest...> {
// parse a digit. recurse with new sum and ramaining digits
static const ULL value = litparser<
(Head <'0' || Head >'9') ? throw std::exception() :
Sum*10 + Head-'0' , Rest...>::value;
};

// When 'Rest' finally is empty, we reach this terminating case
template<ULL Sum> struct litparser<Sum> {
static const ULL value = Sum;
};

Using this machinery in combination with an option like -Werror-narrowing gives a pretty simple and solid solution. (That flags works with gcc and clang, if you know how to prevent narrowing conversions on other compilers, please comment). In any case, at least a warning is required by the standard, and warnings should be taken seriously.

Using this in practice

In practice I prefer to not return a raw integer from the literal operator, but a little wrapper class that identifies that this is a number of steps, and not just any integer. Something as simple as this would do:

struct NrOfSteps {
const int value;
explicit constexpr NrOfSteps(int i) : value { i } {}
}

And the use in _steps could look like this:

template<char... Chars>
NrOfSteps operator"" _steps(){
return NrOfSteps{litparser<0,Chars...>::value};
}

Understanding the meta-programming

The template meta program above can be confusing, especially if you are not used to functional programming. It’s works by recursion. For example, for 123_steps, first _steps is called with arguments {‘1’,’2’,’3’}:

NrOfSteps operator"" _steps() [with char ...Chars = {'1', '2', '3'}]

In steps, we make a litparser template with <0, Chars…>. That becomes:

const ULL litparser<0ull, '1', '2', '3'>::value

Now, in turn, in the initialization of value, we make a new template instantiation with < Sum*10 + Head-‘0’, Rest… > . In this case Sum was 0, and Head is ‘1’ so we end up with:

const ULL litparser<1ull, '2', '3'>::value

which in turn instantiates the template

const ULL litparser<12ull, '3'>::value

which in turn instantiates the final template, the end-case with just a single template parameter, where the accumulated Sum is assigned exposed as value:

const ULL litparser<123ull>::value

References and more

For an introduction to variadic templates have a look at the Variadic Templates are Funadic video by Andrei Alexandrescu, from GoingNative2012. https://channel9.msdn.com

For more about user+defined literals, have a look at Andrzej Krzemieński’s series User Defined Literals

Also have a look at:

http://en.cppreference.com/w/cpp/language/parameter_pack

and

http://en.cppreference.com/w/cpp/language/user_literal

Finally, this post is based on my question and self-answer at stackoverflow, so I would like to thank the users of SO. The template meta program I constructed based on other examples such as these, but I find my use of a terminating case for empty list more clean than terminating on one remaining character.


C++11 Style - Never write “new” or “delete” again - And the make_unique implementation of S.T.Lavavej

One of the most striking changes with the modern C++ style that comes with the new standard from last year, C++11, is the idea that we should not write new or delete again!

In the past, the most important reason for writing “new” was to create an object that could be returned from a function or method without the overhead of copying the new object. The reason this is no longer required is called move-semantics. Among other things, move semantics mean that when you return an std::vector<std::string> by value, the contents are not copied, but transferred, moved. For the details on how that is possible, I give a few starting points a the end of this post.

Now, what should we do instead of newing up raw pointers? Here is an example:

Instead of writing

std::vector<double>* makeVector(){   
std::vector<double>* newVec = new std::vector<double>();
for(int i=0;i<30;++i){
newWec->push_back(i);
}
return newVec;
}

we should simply write:

std::vector<double> makeVector(){   
std::vector<double> newVec();
for(int i=0;i<30;++i){
newWec.push_back(i);
}
return newVec;
}

This has a number of benefits. It’s cleaner, it’s as fast as using raw pointers, and it’s automatically exception safe, since it’s using the RAII idiom. RAII means that all resources are held by objects with destructors, so that no resource (in this case the array and its contents) can be lost/leaked/forgotten. 

In this case it means that the destructor of the vector will be called as soon as the vector is not needed anymore. Raw pointers do not have destructors which deallocate the held object, so we would have to make sure that someone, somewhere will always call delete (once) on the pointer, and that the object is never referenced after that. That has turned out to be very hard.

Return by smart pointers - unique_ptr and shared_ptr

The absolute majority of classes in the C++11 standard library are move-aware, so there is no reason to return values by raw pointer any more. There are a few exceptions - Classes that do not have move-constructors, and which objects are impossible or expensive to copy. An example is the new container std::array. If we follow the rule to never use new or delete, a function returning an array could look like this:

using LargeArray= array<int,10000>; // This is the new type of typedef: Defines a type: 10000 ints

LargeArray giveMeMyArray(){
LargeArray myObj;
myObj.at(3)=5;
return myObj;
}

this is exception safe and clean, but very inefficient since the array is copied out (in this simple example this may not be true, due to return-value-optimization, but that’s not the point). Instead, we reach for a unique_ptr, a smart pointer that behaves similarly to an old-style pointer, but with two important exceptions: 1. It has a destructor that deletes the pointed to object at destruction. 2. It is moveable but not copyable.

This is the most direct way to rewrite our function using unique_ptr:

unique_ptr<LargeArray> giveMeMyArray(){
unique_ptr<LargeArray> myObj(new LargeArray());
myObj->at(3)=5;
return myObj;
}

This is fine, but it breaks our rule of thumb: never use new. To get around that it is agreed best-practice to use a generic helper function called make_unique.

Using make_unique, the code looks like this:

unique_ptr<LargeArray> giveMeMyArray(){
auto myObj = make_unique<LargeArray>();
myObj->at(3)=5;
return myObj;
}

This follows the same pattern as for the other smart pointer in the C++ standard library: shared_ptr, with the helper functions make_shared and allocate_shared.

Using make_unique is not only more clean (in that the advice about new becomes more solid), but is actually also required for exception safety in pretty normal use cases (Se the list of references at the end of this post).

The make_unique implementation of Stephan T. Lavavej

Unfortunately, make_unique did not get into the C++11 standard, so we have to provide it ourselves. The following implementation of make_unique has been suggested by C++ standard-libraries developer Stephan T. Lavavej. For his own explanation, look at his c9Video: Core C++ 6/n, starting at the 48 min mark. Here’s the code:

/* stephantl_make_unique.h
* Based on code by Stephan T. Lavavej at http://channel9.msdn.com/Series/
* C9-Lectures-Stephan-T-Lavavej-Core-C-/STLCCSeries6
*/

#ifndef STEPHANTL_MAKE_UNIQUE_H_
#define STEPHANTL_MAKE_UNIQUE_H_

#include <memory>
#include <utility>
#include <type_traits>

namespace fut_stl {
namespace impl_fut_stl {
template<typename T, typename ... Args>
std::unique_ptr<T> make_unique_helper(std::false_type, Args&&... args) {
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}

template<typename T, typename ... Args>
std::unique_ptr<T> make_unique_helper(std::true_type, Args&&... args) {
static_assert(std::extent<T>::value == 0,
"make_unique<T[N]>() is forbidden, please use make_unique<T[]>(),");
typedef typename std::remove_extent<T>::type U;
return std::unique_ptr<T>(new U[sizeof...(Args)]{std::forward<Args>(args)...});
}
}

template<typename T, typename ... Args>
std::unique_ptr<T> make_unique(Args&&... args) {
return impl_fut_stl::make_unique_helper<T>(
std::is_array<T>(),std::forward<Args>(args)... );
}
}
#endif

This code contains a single template function make_unique and two helper classes. My only modification from the code found in STL’s video is that I placed make_unique in a namespace: fut_stl, and within that namespace, I placed the helper classes into a helper namespace. I find this to be clearer, and it also helps auto-completion (for example in Eclipse and Visual Studio) to not have implementations details be named make_*. Here are the three examples, directly from the same video:

#include "stlav_make_unique.h"
#include <iostream>
#include <ostream>
#include <string>

int main(){
using namespace fut_stl;
using namespace std;
auto a = make_unique<int>(1729);
cout << *a << endl;

auto s = make_unique<string>(5, 'x');
cout << *s << endl;

auto b = make_unique<int[]>(11, 22, 33);
cout << b[0] << " "<< b[1] << " "<< b[2] << endl;
}

This is extremely useful, and you don’t have to understand why it works. The advantage of this version of make_unique over other implementations is that it works with arrays (here I mean int[] for example) while also preventing improper use. If you are interested I strongly recommend following the STL Video series I link to below. Even as a C++ beginner, you should however learn how unique_ptr (as well as shared_ptr) works.

References and more

Any level:

Introductory -

Andrzej’s C++ blog

Intermediate - “Rule of zero”, about the use of unique_ptr for class members:

Above Intermediate - Stephan T. Lavavej. Videos:

Above Intermediate - Herb Sutter: (about exception safety of make_unique and more)

Standard library references:

.

Compiling and using Boost with MinGW and Eclipse

Boost is a very large set of high quality, portable C++ libraries. Boost is useful in many very different areas. The examples mathematical functions, uuid, and C++/Python interaction should give you a flavor of boosts diversity. Much of what is now in C++11 used to exist only via boost. Perhaps the most prominent example is shared_ptr.

Boost is very easy to install. In this short post I’ll post my short recipe for compiling Boost and configuring Eclipse to use it.

1. Compile Boost using MinGW-Builds

I’ll assume you got my MinGW-setup described in my last post. That means that we already have a working installation of MinGW and Eclipse.  If you use another setup with say, GCC under Linux, the steps are very similar. This will give you a full setup for boost 1.52 for GCC 4.7.2 under Windows:

First, download the boost source code. I got the file boost_1_52_0.zip from http://www.boost.org/users/download.
Extract the complete contents of the archive. I placed it at F:\coding\boost_1_52_0 .

Open a terminal (by running command.exe, or the significantly nicer ConEmu).

Then compile like this:

cd F:\coding\boost_1_52_0

.\bootstrap.bat

.\b2 --prefix=F:\coding\mingwposix_installs64 toolset=gcc variant=debug,release link=static,shared threading=multi install -j7

The directory F:\coding\mingwposix_installs64 is where I’d like the results to end up. Modify it as you need.

This should be it. If you have trouble, ask me, or read the full instructions from boost.

2. Setup Eclipse to use boost

First clone the example C++11 project I made in the previous post. Then, all under Project/properties/ and C/C++ General at Paths and Symbols:

  • Add the library path:
    F:\coding\mingwposix_installs64\lib
  • Under Includes / GNU C++, add the include path
    F:\coding\mingwposix_installs64\include\boost-1_52
  • Under libraries, add the specific boost libraries you need.
    For example I have added:

    boost_thread-mgw47-mt-d-1_52
    boost_system-mgw47-mt-d-1_52
    the ‘d’ is for debug. If you configure both debug and release builds you need to make sure you specify the right library for the right kind of build.

    Note that most of boost is headers-only. That means that you often don’t need to link in a single lib.

That’s it. You should be able to compile any of these examples:


PS.

You can list all your boost libraries with something like
dir F:\coding\mingwposix_installs64\lib\*-d-*52.a

Among others, you should have

libboost_system-mgw47-mt-d-1_52.a
libboost_thread-mgw47-mt-d-1_52.a

Note that you should not include the ‘lib’ part at the beginning of the library name, and also not the file name extension.



Setup for C++11: Option 2/n: using Eclipse and MinGW-builds [on Windows]

This is my third post about C++11.

In the last post I covered how to get started by using Visual Studio and the CTP. That’s fine if you are already used to visual studio, but if you would like to explore more of C++11, you currently need to turn to other compilers.

In this post I’m going through how to get going with a first C++11 program using MinGW-builds and Eclipse.

With this setup you get the complete gcc-4.7.2 support for C++11, including

  • std::future, std::async and std::thread missing in other Windows-versions of gcc.
  • initializer lists and other things still missing in Visual Studio.

MinGW is a minimalist development environment for native Microsoft Windows applications. (There are also other ways to install gcc on windows, such as cygwin). Currently no standard version of cygwin or MinGW support any of the C++11 features that are related to threads.

"MinGW-Builds" does NOT have those problems. Getting this setup is not hard but requires a few clicks, so it may take you something like half an hour depending on your experience.

Here’s what I’ll cover:

  1. Install the gcc compiler
  2. Install Eclipse
  3. Start Eclipse and create an example project
  4. Compile and run an example program (with or without the debugger)
  5. Trouble?
  6. Example C++11 program.

1. Install gcc: MinGW-Builds

  1. Download MinGW-Builds.
    The version I got was x64-4.7.2-release-posix-sjlj-rev1.7z. The fact that posix is in the name indicates that the threading model is posix. That’s currently key to getting the gcc support for C++11 threads working on Windows.
  2. Extract the directory mingw to any location - No installation required or possible. I put it at F:\coding\mingw
  3. Add the compiler to you PATH environment variable. Open the settings program ‘Edit Environment Variables for Your Account’, or from the control panel, Make changes to your user account/Change my environment variables: Add a new User variable PATH, and add the following:

    F:\coding\MinGW\bin;F:\coding\MinGW\msys\1.0\bin

    Make sure the two directories actually do exist, and that they are separated by a ; character. 

You need to log out for this to take effect!

To verify that you got it right, you can open a command prompt, and write

g++ --version 

You should get a response like this, mentioning MinGW-builds:

g++ (Built by MinGW-builds project) 4.7.2 
Copyright (C) 2012 Free Software Foundation, Inc. ...

2. Install Eclipse

Download “Eclipse IDE for C/C++ Developers" from http://www.eclipse.org/downloads/ (I used eclipse-cpp-juno-SR1-win32-x86_64.zip)

- Just extract the zip file- No installation in required.

My eclipse directory is put at F:\coding\ , it does not matter at all. Optionally,  make a shortcut from the eclipse application found at e.g. F:\coding\eclipse\eclipse.exe to your desktop.

3. Start Eclipse and create an example project

  1. Run eclipse.exe
  2. When asked, specify a new workspace location, for example F:\coding\workspace
  3. Ignore any warnings about Git, EGit and HOME not being set. You can return to that later if you would like to use Git.
  4. Close the Welcome to Eclipse window (upper left corner).
  5. Make a new project under the top menu File/ new /C++ Project

    - Enter a project name ‘MyFirstCpp11Program’
    - Select Toolchain MinGW GCC. (You may need to de-select the marker ‘Show project types and toolshains …’)
    - Finish.

  6. Enable C++11 for this project:

    This makes Eclipse use C++11 both for compiling and linking, as well as for building an index of known names used by the graphical interface.
    EDIT: Note, when using other builds of gcc (also on Linux) I also had to add -pthread to all places where I add -std=c++11 below:

    For newer versions of eclipse: Eclipse Juno and later.
    [Eclipse C/C++ Development Tools 8.1.1]


    • Select the Properties window from the Project menu. Go to the Settings sub-menu under C/C++ Build.
      Select [ All configurations ] at the top, and add the option -std=c++11 to the field Other flags Under both GCC C++ Compiler/Miscellaneous and GCC C++ Linker/Miscellaneous.
    • Under C/C++ General (again in project properties), find the Preprocessor Include Path and go to the Providers Tab. Deselect all except CDT GCC Builtin Compiler Settings. Then untag Share settings entries … . Add the option -std=c++11 to the text box called Command to get compiler specs.
    • Go to paths and symbols (again under Under C/C++ General). Selects the Symbols tab, click restore defaults, and then click Apply.

    For older versions of eclipse: (Eclipse Indigo)

    [eclipse C/C++ Development Tools Version: 8.0.2]

    • Select the Properties window from the Project menu. Go to the Settings sub-menu under C/C++ Build.
      Select [ All configurations ] at the top, and add the option -std=c++11 to the field Other flags Under both GCC C++ Compiler/Miscellaneous and GCC C++ Linker/Miscellaneous.
    • Under C/C++ Build (again in project properties), find Discovery Options and add select Discovery profile scope ‘Configuration-wide;. Then add   -std=c++11 to the C++ Compiler invocation arguments.
      Click ‘Clear’ at ‘Clear discovered entries now’.
    • You will need to wait a while for the indexer to complete.

Done!

4. Compile and run and example program (with or without debugger)

My example C++11 program is found at the end of the post. Replace the example program with my example. You can just copy-paste it in place.

  • Build the project by clicking the little Hammer at the top.
  • Run the program by clicking the green play-button.

It should print, among other things, ‘rain amount on Friday:16’. If you can’t find the output, it’s found on the Console tab at the bottom of the Eclipse window. Look for a list of consoles under the icon that looks like a monitor.

You can also run the debugger. Just click the spider (or F11) instead of the play-button. You will need to click F8 (resume) to start the execution, and jump over any break points (which you set by double clicking to white/light gray area to the left of the code). Press the red stop button, or ctrl-F2 top stop.

5. Trouble?

  • If you have trouble compiling or running my examples you may have forgotten to click Apply while configuring the Eclipse project. Eclipse is (or at least has been in the past) picky - do it every time you leave a settings tab.

  • If eclipse still gives you red lines under lock_guard and mutex, first try to modify the source code arbitrarily and recompile, or select Index/rebuild after right clicking on the project in the project explorer.

  • When using other builds (than MinGW-builds) of gcc (also on Linux) I also had to add -pthread to all places where I added -std=c++11 above.

Unfortunately, Eclipse seems to anyhow not understand std:future and std::async, so a few lines related to them will still have a red underline.

Older versions of Eclipse also does not understand how find the members of a class held by shared_ptr. The actual gcc compiler, via MinGW-builds, will understand them correctly.

Update: To upgrade the C++ support in Eclipse, update the CDT by selecting Help/Install New Software. Add the CDT repository (currently http://download.eclipse.org/tools/cdt/releases/juno ), and upgrade all CDT Main Features. For future reference, you’ll find the link to the latest repository at http://www.eclipse.org/cdt/downloads.php

The C++11 support in CDT is evolving quickly, so you may want to try out the nightly builds. It’s as easy as specifying the repository:
http://download.eclipse.org/tools/cdt/builds/kepler/nightly

There seems be no way to downgrade, so be careful (backup your important projects). I had no trouble so far.

I would be very happy for feedback!


In the NEXT post I cover how to compile and use the high-quality Boost C++ libraries with MinGW and eclipse.


6. Example C++11 program


// FirstCPP11_Example.cpp : Defines the
// entry point for the console application.
//
// C++11 Example, Johan Lundberg 2012
// http://scrupulousabstractions.tumblr.com

#include<mutex>
#include<future>
#include<vector>
#include<iostream>
#include<stdexcept>
#include<chrono>
#include<string>

class WeatherServer {
public:
WeatherServer() : current_temp(0) {};
~WeatherServer() {};

/* Method calculating forcast for day, for
* simplicity given as a plain integer. */
int CalculateForecast(unsigned int i){

/* Lock the mutex, using RAII, for the
* duration of this calculation (for show).
* Removing this will allow multiple
* forecast calculations to run at the same time.
* Else they will wait for each other */
std::lock_guard<std::mutex> locker(members_mutex);

/* Sleep for some time just to show what's going on */
std::chrono::milliseconds dura( 701 );
std::this_thread::sleep_for( dura );

std::cout << "CalculateForecast done for i=" <<i<<std::endl;
// result is just the square of the input...
return i*i ;
}
private:
int current_temp;
std::mutex members_mutex;
};

void my_main(){
auto myWS=std::make_shared<WeatherServer>();
std::vector<std::future<int>> forecasts;

int v[]={0,1,2,3,4,5,6,7} ;

for(auto i: v ){
// add a background calculation to the list
forecasts.push_back( std::async(std::launch::async,
[i,myWS]() { return myWS->CalculateForecast(i); } ));
}

/* This line will not compile if you use visual studio older
* than the CTP Nov 2012: Current versions of visual studio will
* underline it with red lines, but the actual compiler
* understands it. Alternative for older compilers:
std::string ctpTestString("Hello \"World!\" ");
*/
std::string ctpTestString=R"( Hello new "World!" )" ;

std::cout << ctpTestString<<std::endl;

int rainOnMonday = forecasts[0].get() ;
int rainOnFriday = forecasts[4].get() ;

std::cout << "rain amount on Monday:" << rainOnMonday <<std::endl;
std::cout << "rain amount on Friday:" << rainOnFriday <<std::endl;
std::cout << "hit enter to exit. " <<std::flush ;
std::cin.ignore(1);

}

int main(){
try{
my_main();
}catch(std::exception& e){
std::cout << "main got exception:" << e.what() <<std::endl;
throw;
}catch(...){
std::cout << "main got unknown exception." <<std::endl;
throw;
}
}




Setup for C++11: Option 1/n: using Visual Studio 2012 + ‘CTP’


In this post I’ll use Visual Studio to write a short C++11 program that runs a few calculations asynchronously, making use of for example the new so called std::future.

Microsoft is actively working on C++11 support and plan to ship compiler backend upgrades between the major releases of visual studio. At this writing, the last such upgrade is known as v120_CTP_Nov2012. Even with this upgrade a few major things are missing. Most notably for a beginner, the new curly-brace initialization syntax via initializer_list is still missing. Still, much is there and worth exploring. This is how you get going:

Installing the latest version of Visual Studio:

  1. Install Visual Studio 2012. The express version is free and it will do. If you work on windows 7, use the ‘Desktop’ version. When asked about what to install, you can deselect everything except C++.
  2. Install Visual Studio updates - You only need vsupdate. This will update your Visual Studio installation.
  3. For the latest and most complete C++11 support from Microsoft, install their CTP (Community Technical Preview).

Creating a first C++ project:

  1. Open VS Express for Desktops.
  2. From the tab to the left, select New Project
  3. Select Win32 Console Application from the path ‘Installed/Templates/Visual C++’. Before you click OK pic a Name for your new application, such as MyFirstCpp11Program. Then select Finish.

Enable the latest C++ features from the CTP we installed:

  1. On the menu bar, select PROJECT/MyFirstCpp11Program Properties…
  2. Then find Configuration Properties/ General
  3. Change Platform Toolset from v110 to the latest CTP. As of this writing it Microsoft Visual C++ Compiler Nov 2012 CTP (v120_CTP_Nov2012)
  4. if you don’t know what it is, disable Precompiled Headers under C/C++ precompiled headers.
  5. Enable line numbers. I find that very helpful. You just need to click the box under the menu TOOLS/Options/Text Editor/All Languages/Display

Your program will initially look something like this:

#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[]){
return 0;
}

To try out the new features in C++11, remove all of that code, and instead insert my example, found at the end of this post.

To compile and run the program, press the green arrow: ‘Local Windows Debugger’.

There are many places to learn more about using visual studio. If you never did that before, try setting break points where the debugger will pause during the execution. Break points are created by double clicking the gray area to the left of the code, left of the line numbers if you followed my advice above to enable them.

Good luck!

Example C++11 Program



// FirstCPP11_Example.cpp : Defines the // entry point for the console application. // // C++11 Example, Johan Lundberg 2012
// http://scrupulousabstractions.tumblr.com/ #include<mutex> #include<future> #include<vector> #include<iostream> #include<stdexcept> #include<chrono> #include<string> class WeatherServer { public: WeatherServer() : current_temp(0) {}; ~WeatherServer() {}; /* Method calculating forcast for day, for * simplicity given as a plain integer. */ int CalculateForecast(unsigned int i){ /* Lock the mutex, using RAII, for the * duration of this calculation (for show). * Removing this will allow multiple * forecast calculations to run at the same time. * Else they will wait for each other */ std::lock_guard<std::mutex> locker(members_mutex); /* Sleep for some time just to show what's going on */ std::chrono::milliseconds dura( 701 ); std::this_thread::sleep_for( dura ); std::cout << "CalculateForecast done for i=" <<i<<std::endl; // result is just the square of the input... return i*i ; } private: int current_temp; std::mutex members_mutex; }; void my_main(){ auto myWS=std::make_shared<WeatherServer>(); std::vector<std::future<int>> forecasts; int v[]={0,1,2,3,4,5,6,7} ; for(auto i: v ){ // add a background calculation to the list forecasts.push_back( std::async(std::launch::async, [i,myWS]() { return myWS->CalculateForecast(i); } )); } /* This line will not compile if you use visual studio older * than the CTP Nov 2012: Current versions of visual studio will * underline it with red lines, but the actual compiler * understands it. Alternative for older compilers: std::string ctpTestString("Hello \"World!\" "); */ std::string ctpTestString=R"( Hello new "World!" )" ; std::cout << ctpTestString<<std::endl; int rainOnMonday = forecasts[0].get() ; int rainOnFriday = forecasts[4].get() ; std::cout << "rain amount on Monday:" << rainOnMonday <<std::endl; std::cout << "rain amount on Friday:" << rainOnFriday <<std::endl; std::cout << "hit enter to exit. " <<std::flush ; std::cin.ignore(1); } int main(){ try{ my_main(); }catch(std::exception& e){ std::cout << "main got exception:" << e.what() <<std::endl; throw; }catch(...){ std::cout << "main got unknown exception." <<std::endl; throw; } }

C++11 - “It feels like a new language”

C++11 is the new version of C++ standardized last year. It contains many additions that help in making more powerful abstractions, more portable code, and in general an easier life for C++ developers.

There are are many great resources out there on C++11, such as

Compiler Support:

A base of common functionality supported by the mainstream compilers has started to form, but there is still no compiler that supports everything mandated by the new standard. Herb Sutter (Microsoft) has stated that during 2013 he expects at least two (not specified) compilers will have practically complete support.

Today, the compilers leading the chaise for C++11 compatibility are GCC and Clang. With gcc 4.7.2 (which ships with Ubuntu 12.10), you already get very good support, and the things that are not supported are mostly distinct and separate, such as parts of standard library support for regular expressions.

In the next post I’ll go through how to get a C++11 setup using Visual Studio and the new additions found in the so called Community Technical Preview from Microsoft.

Scrupulous Abstractions

I’m Johan Lundberg - an Experimental Particle Physicist who work as a software consultant for afconsult, in Stockholm. Before that I worked for at the ATLAS particle detector at LHC, , Geneva, and then at Stockholm University. Before that I did my PhD on Astro-Particle physics, working on the detection of Ultra-High Energy Neutrinos using the detector at the South Pole, Antarctica.

This is my programming blog. As a start I’m going to use it for sharing ideas and experiences about C++11, the new C++ standard.

The ultimate reason for starting this blog was to have a place where I can structure and test what I learned so far. A year ago, while at paternity leave, I spent some time at stackoverflow (me) trying to learn and write good answers on Python and C++. Perhaps I’ll elaborate here on some of my favorite answers, by me or others. A couple of weeks ago I prepared two short seminars on C++11 and Modern C++ style and found I didn’t have a good collection of my experiments. This blog will be a place where I can collect material for the future. Some will be very basic, like configuring Visual Studio or Eclipse, while some may become more esoteric.

I’ll keep things clear enough so that I can go back and understand it. I imagine that will also mean that some of the contents can be of interest to others.

  - Johan Lundberg, Nov 2012

PS.
This is my first tumblr blog. The blog theme is originally based on The Minimalist but completely redesigned both in shapes and colours. I added the post list on the upper right corner, backed by feed2js.org.
I also added support for C++ and Python syntax high lighting using SHJS, with a custom colour set. The syntax highlighter is rather simple, and also does not know about C++11, but it’s still useful. This is how it looks:

#include <iostream>
#include <future>
#include <memory>
#include <string>
#include <vector>

#using namespace std;
int main() { cout << "Hello " << endl; auto x={"egg","foo","baar","/","some","text"};
for( auto &a : x) {
cout << a <<endl;
SomeClass mineA(a);
SomeClass mineB{a};
int qA=3;
int qB={3};
int qC{3};
[=,&qA](int a,float b,string c){ return qA[a]; }(1,2.1,"3");
}
}