Category Archive for Software Development

C++14 STL Features, Fixes, And Breaking Changes In Visual Studio 14 CTP1

Stephan T. Lavavej, aka STL, has written a very detailed blog post describing new C++14 STL features, implemented fixes, and breaking changes in Visual Studio 14 CTP1. Read it here.

One notable breaking change is that containers cannot have const elements:

The Standard has always forbidden containers of const elements (e.g. vector, set). (C++98/03’s prohibition was crystal clear: elements must be Assignable, which const T isn’t. C++11/14’s prohibition is obscurely hidden, but it’s there.) Previously, VC accepted such containers due to non-Standard machinery in std::allocator. We’ve removed that machinery, so such containers now fail to compile.

Share

Visual Studio “14” CTP

Microsoft has released Visual Studio “14” CTP. You can read the announcement on Soma’s blog. Visual Studio “14” will most likely be available sometime in 2015.

Note: This is a CTP release, thus it should be installed in a test environment, such as a VM or a clean machine. Do not install on a machine with another version of Visual Studio installed.

Specifically for C++, there are quite a few improvements, such as:

  • Generalized lambda capture
  • User-defined literals in the language and standard library
  • Completed noexcept
  • Inline namespaces
  • Thread-safe “magic” statics
  • Unrestricted unions
  • All November 2013 compiler CTP features
  • Null forward iterators
  • quoted()
  • Heterogeneous associative lookup
  • integer_sequence
  • exchange()
  • get()
  • Dual-range equal(), is_permutation(), mismatch()
  • tuple_element_t
  • Filesystem “V3″ Technical Specification (TS)
  • Object file size reductions
  • Debug checking fixes
  • Create declaration or definition
  • Native memory diagnostics
  • Refactored C Runtime (CRT): This CTP contains the first preview of the substantially refactored CRT. msvcr140.dll no longer exists. It is replaced by a trio of DLLs: vcruntime140.dll, appcrt140.dll, and desktopcrt140.dll.

Read Eric’s blog for a bit more details on those improvements.

Download the CTP.

Share

Introduction to WIC: How to use WIC to load an image, and draw it with tranparency using only GDI?

A while ago I wrote an article: “Introduction to WIC: How to use WIC to load an image, and draw it with GDI?”

The code in that article didn’t handle transparency.
It’s actually trivial to implement transparency in that sample code. Read the rest of this entry »

Share

Modern C++ Tips and Tools

C++ allows you to write clean, safe and fast code, and writing it is even easier than ever thanks to new features in C++11 and C++14. This article highlights a couple of tips.

Comments & ‘Cleverness’

Code gets read a lot more often than it gets written, so make sure that your code can be read and understood in the future, by yourself and by other developers. This means that you have to add comments, and that you should avoid trying to make code as terse and ‘clever’ as possible; because that hurts readability.

Memory Management

In modern C++ you should avoid any explicit calls to delete operators or functions to deallocate memory such as free(). Code that relies on such explicit calls is susceptible to memory leaks. For example:

void foo(size_t size) {
    char* buffer = new char[size];
    // ...
    delete [] buffer;
}

The code is straightforward; it allocates memory, does something with the memory, and then deletes the memory. It uses a ‘naked’ pointer, which you have to manage yourself. This piece of code causes a memory leak if an exception is thrown before the delete operator is called. You should avoid using naked pointers, instead use encapsulation objects that automatically handle the memory. For example, the above code should be written using a container such as a vector:

void foo(size_t size) {
    std::vector buffer(size);
    // ...
}

Using a container, there is no need to free the memory, the destructor of the container will handle all that for you. Similarly, if you need dynamically allocated objects, do not store them in naked pointers, instead use smart pointers such as std::unique_ptr, which is not reference counted, or if you need shared ownership, std::shared_ptr, which is reference counted. unique_ptr will automatically delete the object when the unique_ptr goes out of scope. An object wrapped in a shared_ptr is automatically deleted when the reference count goes to zero.

When you use unique_ptr, use std::make_unique<>(). Similarly, use std::make_shared<>() when you use shared_ptr.

One key point to remember: never use std::auto_ptr, it has officially been deprecated because of its problems. One of its problems is that it is forbidden to store them in STL containers because auto_ptr does not meet C++98/03’s requirements for container elements.  unique_ptr  and shared_ptr don’t have any of these problems and are perfectly safe to use in STL containers.

The auto Keyword

Use auto to let the compiler deduce the type of variables automatically. This helps a lot with complicated types that are hard or even impossible to write. For example:

std::map<std::string, std::vector> myMap;
for (std::map<std::string, std::vector>::iterator iter = begin(myMap);
     iter != end(myMap); ++iter)
{
    //...
}

This is complicated, difficult to write and error prone.
Note that since C++11 it’s recommended to use the non-member functions std::begin(), end(), cbegin(), cend(), rbegin(), rend(), crbegin(), and crend() instead of the member functions.
Using the auto keyword the above can be rewritten in a very clean way:

for (auto iter = begin(myMap); iter != end(myMap); ++iter) { ... }

Using the range-based for loop, the code can be written even more elegantly:

for (auto&& item : myMap) { ... }

Or:

for (auto& item : myMap) { ... }

Or:

for (const auto& item : myMap) { ... }

Never write the following, unless your container only contains primitive types:

for (auto item : myMap) { ... }

If you use this for containers with non-primitive elements performance will suffer because item will be a copy of each of the elements in the container.

nullptr

Do not use NULL for pointers, use the nullptr keyword. NULL is a macro for 0 which can sometimes result in problems that are hard to track down. nullptr is really a null pointer type and is not just a macro for 0.

Move Semantics

Move semantics since C++11 helps with performance, allowing objects to be moved instead of copied. It is based on rvalue references, represented as &&. C++ automatically uses move semantics in cases where the source object will cease to exist. You can explicitly move an object by using std::move(). The STL also supports move semantics. To add move semantics to your classes you only need to implement a move constructor and move assignment operator which have the following prototype:

MyObject(MyObject&& src);               // Move constructor
MyObject& operator=(MyObject&& rhs);    // Move assignment operator

Lambda Expressions

Lambda expressions are a powerful addition to the C++ language. One huge benefit is that they make it much easier to use STL algorithms. For example, you can use the count_if() algorithm in combination with a simple lambda expression to count all elements in a vector that are less than 0.

std::vector vec;
auto count = std::count_if(cbegin(vec), cend(vec),
    [](int i){ return i < 0; });

Investing time in learning about lambda expressions will pay itself off quickly.

Threading

You should read up on the threading functionalities introduced in C++11. One useful and often overlooked function is std::call_once(), used to make sure that a specific callable entity is executed exactly one time, no matter how many threads call it simultaneously. This can for example be used to make a compact and thread safe implementation of the singleton pattern.

Strings

Text matching, parsing, and searching can be tricky and complicated, especially when it should work with Unicode strings. You should avoid writing your own functions to perform such operations, instead use classes from <regex> such as std::wregex.

C++11 supports raw string literals. They are extremely useful in the context of regular expressions. For example, the following regular expression searches for spaces, newlines, and backslashes:

string s = "( |\\n|\\\\)";

The last 4 backslashes are correct. If you want to match a backslash, it needs to be escaped in the regular expression, thus \\. If you want to write \\ in a normal string literal, you need to escape both backslashes, resulting in 4 of them. Using raw string literals you simply write:

string s = R"(( |\n|\\))";

R”( and )” denote the boundary of the raw string literal.

Random Numbers

If your application needs to generate random numbers, don’t use the old C style srand()/rand() functions. Their randomness is not good. Instead, use <random>, which contains classes to generate random numbers, such as a Mersenne Twister, and supports different mathematical distributions, for example a uniform distribution, a Poisson distribution, and so on.

Further Reading

Take a look at “Professional C++ 2nd Edition” if you are determined to master C++, including all C++11 features.

Share

Announcing the Visual C++ Compiler November 2013 CTP

Visual Studio 2013 has only been released very recently, and the Visual C++ team already has a new CTP out with new features :)
The following table gives an overview and even includes features that are planned for future releases.

  • Implicit move special member function generation (thus also completing =default)
  • Reference qualifiers on member functions (a.k.a. “& and && for *this”)
  • Thread-safe function local static initialization (a.k.a. “magic statics”)
  • Inheriting constructors
  • alignof/alignas
  • __func__
  • Extended sizeof
  • constexpr (except for constructors)
  • noexcept (unconditional)
  • C++14 decltype(auto)
  • C++14 auto function return type deduction
  • C++14 generic lambdas (with explicit lambda capture list)
  • (Proposed for C++17) Resumable functions and await

Remember, this is a CTP so it does not come with a Go Live license.
More details can be found on the VCBlog.

Share

Visual Studio 2013 Available for Download

The final versions of Visual Studio 2013, Team Foundation Server 2013 and .NET 4.51 are now available from MSDN. You can also download trials.

VS 2013 can be installed side by side with previous versions of Visual Studio or, if you have a VS 2013 pre-release, it can be installed straight on top of the pre-release. TFS 2013 cannot be installed side by side but can also be installed on top of either a previous version (TFS 2012 or TFS 2010) or a pre-release.

Learn more about what’s new in Visual Studio 2013.

What’s new in Visual C++ 2013 (excerpt from MSDN):

  • Compiler
    • Added support for the following ISO C++11 language features:
      • Default template arguments for function templates.
      • Delegating constructors.
      • Explicit conversion operators.
      • Initializer lists and uniform initialization.
      • Raw string literals.
      • Variadic templates.
      • Alias templates.
      • Deleted functions.
      • Non-static data member initializers (NSDMIs).
      • Defaulted functions.  (using =default to request memberwise move constructors and move assignment operators is not supported)
    • Added support for the following ISO C99 language features:
      • _Bool
      • Compound literals.
      • Designated initializers.
      • Mixing declarations with code.
    • String literal conversion to modifiable values can be disallowed by using the new compiler option /Zc:strictStrings. In C++98, conversion from string literals to char * (and wide string literals to wchar_t *) was deprecated. In C++11, the conversion was removed entirely. Although the compiler could strictly conform to the standard, instead it provides the /Zc:strictStrings option so that you can control conversion. By default, the option is off. Note that when you are using this option in debug mode, the STL will not compile.
    • rvalue/lvalue Reference Casts. With rvalue references, C++11 can clearly distinguish between lvalues and rvalues. Previously, the Visual C++ compiler did not provide this in specific casting scenarios. A new compiler option, /Zc:rvalueCast, has been added to make the compiler conformant with the C++ Language Working Paper(see section 5.4, [expr.cast]/1). The default behavior when this option is not specified is the same as in Visual Studio 2012.
  • STL
    • Support for the C++11 explicit conversion operators, initializer lists, scoped enums, and variadic templates.
    • All containers now support the C++11 fine-grained element requirements.
    • Support for these C++14 features:
      • “Transparent operator functors” less<>, greater<>, plus<>, multiplies<>, and so on.
      • make_unique<T>(args…) and make_unique<T[]>(n)
      • cbegin()/cend(), rbegin()/rend(), and crbegin()/crend() non-member functions.
    • <atomic> received numerous performance enhancements.
    • <type_traits> received major stabilization and code fixes.

This list is just a small part of everything that’s new. There are also

  • Visual C++ library enhancements
  • C++ application performance enhancements
  • Diagnostics enhancements
  • 3D graphics enhancements
  • Quite a few very nice IDE and Productivity enhancements.

Read all the details here.

Visual C++ 2013 now also supports “just my code” debugging which makes working with C++ even better. The ability to filter the call stack down to just the code you wrote when debugging has long existed for managed languages and is now available for C++ :)

Share

My Article “Advanced C++ Tips and Tools” on Amazon

My article “Advanced C++ Tips and Tools” is live on the tech.book(store) website of Amazon.

C++ allows you to write clean, safe and fast code, and writing it is even easier than ever thanks to new features in C++11. This article highlights a couple of tips…

You can read the full article here.

Share

Visual Studio 2012 Update 2 Now Available

Microsoft has released Update 2 for Visual Studio 2012 (VS2012.2). You can get it here.

Just as with VS2012.1 (which is installed as part of VS2012.2 for those of you who don’t already have VS2012.1 installed), this release contains important fixes as well as a wealth of new functionality, addressing feedback we’ve received from the community and aligning with key software development trends in the market. The new functionality primarily spans (though is not limited to) five areas of investment: agile planning, quality enablement, Windows Store development, line-of-business development, and the general developer experience.

Check out Somasegar’s blog post for more details on this update.

Share

Visual Studio 2012 Update 1 Now Available


The first update for Visual Studio 2012 has been released.
This update delivers bug fixes, but also new functionality. The new functionality in this first update primarily spans four areas: Windows development, SharePoint development, agile teams, and continuous quality.

We can now target Windows XP again with C++ code, and there have been a couple of C++ unit testing enhancements. For Windows Store applications, the update includes support for both mixed-mode managed/native debugging and for native ARM dump debugging.

Get more details about the update.
Download the update.

Share

Visual C++ November CTP, now with more C++11

As promised, Microsoft is releasing out-of-band updates for Visual C++. A preview of the first such update has now been released as the November 2012 Compiler CTP. This is a Customer Technology Preview and does not come with a ‘Go Live’ license, but it allows you to start experimenting and testing new features, and to provide feedback.

This November 2012 CTP contains a lot of new C++11 features:

  • Variadic templates
  • Uniform initialization and initializer_lists
  • Delegating constructors
  • Raw string literals
  • Explicit conversion operators
  • Default template arguments for function templates

More details, including installation instructions and how to give feedback can be found here.

Download the November 2012 CTP and start playing with these new C++11 features.

Share

Implementing a Thread-safe Singleton with C++11

C++11 makes it easier to write a thread-safe singleton. Here is an example. The class definition of the singleton looks as follows:

#include <memory>
#include <mutex>

class CSingleton
{
public:
	virtual ~CSingleton();
	static CSingleton& GetInstance();

private:
	static std::unique_ptr<CSingleton> m_instance;
	static std::once_flag m_onceFlag;
	CSingleton(void);
	CSingleton(const CSingleton& src);
	CSingleton& operator=(const CSingleton& rhs);
};

The implementation of the GetInstance() method is very easy using C++11 std::call_once() and a lambda:

std::unique_ptr<CSingleton> CSingleton::m_instance;
std::once_flag CSingleton::m_onceFlag;

CSingleton& CSingleton::GetInstance()
{
	std::call_once(m_onceFlag,
		[] {
			m_instance.reset(new CSingleton);
	});
	return *m_instance.get();
}
Share

Kate’s C++ AMP Book

Kate Gregory (a fellow VC++ MVP) has published her book called “C++ AMP: Accelerated Massive Parallelism with Microsoft Visual C++”.

The official description is as follows.

Capitalize on the faster GPU processors in today’s computers with the C++ AMP code library—and bring massive parallelism to your project. With this practical book, experienced C++ developers will learn parallel programming fundamentals with C++ AMP through detailed examples, code snippets, and case studies. Learn the advantages of parallelism and get best practices for harnessing this technology in your applications.

Discover how to:

  • Gain greater code performance using graphics processing units (GPUs)
  • Choose accelerators that enable you to write code for GPUs
  • Apply thread tiles, tile barriers, and tile static memory
  • Debug C++ AMP code with Microsoft Visual Studio®
  • Use profiling tools to track the performance of your code

Find out more about this book here.

Share

BeCPP Meeting October

The next meeting of the Belgian C++ Users Group is planned for Tuesday October 16th 2012 at 18:30 in the Microsoft offices in Zaventem.

The agenda is as follows:

  • Session 1: An introduction to the C++ Network Library (Glyn Matthews)
  • Break
  • Session 2: Comparison between Unit Test Frameworks (Mark Van Peteghem)
  • Drink

Microsoft is sponsoring this event by providing the location, drinks and sandwiches.

The event is free for everyone, but you need to register for it.

Share

Visual Studio 2012 RC Available

Microsoft has made the Release Candidate of Visual Studio 2012 available for download. The release candidate comes with a Go-Live license.

Read Jason Zander blog post for details of this release.

Get it here.

Share

BeCPP Meeting June with International Speakers

The third meeting of the Belgian C++ Users Group is planned for Wednesday June 27th 2012 at 18:30 in the Microsoft offices in Zaventem.

There will be two presentations, and we are proud to announce that they will be given by 2 international top speakers:

  • Kate Gregory is the author of over a dozen books, and speaks at DevTeach, TechEd (USA, Europe, Africa), and TechDays, C++ Connections (with fellow speakers Herb Sutter and Bjarne Stroustrup), among others. Her speaker ratings are consistently in the top 10%. Kate is a C++ MVP, a founding sponsor of the Toronto .NET Users Group, the founder of the East of Toronto .NET Users group, a member of the INETA speakers bureau, and a member of adjunct faculty at Trent University in Peterborough. Since January 2002 she has been Microsoft Regional Director for Toronto and since January 2004 she has been awarded the Microsoft Most Valuable Professional designation for Visual C++. In June 2005 she won the Regional Director of the year award and in February 2011 she was designated Visual C++ MVP of the year for 2010. Kate develops courses on C++, Visual Studio, and Windows programming for Pluralsight and is writing a book on C++ AMP.
  • Rong Lu is a Program Manager in the Visual C++ team at Microsoft. She holds both Bachelor’s and Master’s degrees in Computer Science from Shanghai Jiaotong University. She is now working on Visual Studio vNext Application Lifecycle Management Tools for C++. Before that, she worked on the Visual Studio 2005 SDK, Visual Studio 2008 and 2010 releases, mainly responsible for designing architecture tools and SharePoint development tools. She has been a speaker at TechEd since 2007

Both are experienced speakers, and it’s a perfect opportunity for networking. If you ever wanted to ask a question to a member of the Visual C++ product team, now is your chance.

The agenda will be as follows:

  • Session 1 (18:30 – 19:30): What’s new in VC++11 (Rong Lu)
  • Break
  • Session 2 (19:45 – 20:45): C++ AMP (GPGPU Computing) (Kate Gregory)
    It is time to start taking advantage of the computing power of GPUs. C++ AMP can deliver orders of magnitude performance increase with certain algorithms by utilizing the GPU to perform mathematical calculations.
  • Drink

Microsoft is sponsoring this event by providing the location, drinks and sandwiches.

The event is free for everyone, but registration is required. Register now.
A limited number of seats are available.

( PS: If you know anyone interested in C++, please forward this invitation to them. )

Share

Visual Studio 11 UI Updates Coming in RC

Most op you will know by now that the Visual Studio 11 Beta UI is rather gray. There was a lot of feedback about this from the communities, and it seems Microsoft is listening. They have announced a couple of UI changes to bring back some color to the UI.

Check out this blog post for a description of the changes, including before and after screenshots. I definitely like the new upcoming changes :)

Share

Visual Studio 11 Beta Announced

Microsoft has announced that it will release Visual Studio 11 Beta on 29th of February, and that it will be “go live,” meaning you will be allowed to start using it in production environments. Read the official announcement.

The user interface of the new Visual Studio 11 is completely overhauled. It now follows the Metro principles of clean UI that uses typography and white space for layouting instead of lines. Below are two screenshots of the UI in the beta version.


As you can see, it’s completely different compared to Visual Studio 2010. Themes are supported, so you’ll be able to design whatever theme you want. An in-depth discussion of these changes can be found on the Visual Studio Team Blog.

The product pages have also been updated with information about the upcoming releases. One new version of the product is called “Team Foundation Server Express Beta”, which is a free collaboration software targeted at small teams. Read more about it here.

Share

Double precision support in C++ AMP

Daniel Moth from the C++ AMP development team has posted an interesting blog post about double precision floating point arithmetic support in C++ AMP and its limitations on current hardware.

Read it here.

Share

C++ AMP Open Specification Published

As promised, Microsoft has released an open specification of C++ AMP: Accelerated Massive Parallelism :)
This allows other compiler vendors to implement support for C++ AMP on any platform.

Read the official announcement.

Download the specification.

Share

Mandelbrot Using C++ AMP

It is time to start taking advantage of the computing power of GPUs…

A while ago I wrote an article about how to use the Microsoft Parallel Patterns Library (PPL) to render the Mandelbrot fractal using multiple CPU cores. That article can be found here.

This new article will make the Mandelbrot renderer multiple times faster by using a new Microsoft technology called C++ AMP: Accelerated Massive Parallelism, introduced in the Visual C++ 11 Preview.

Read the rest of this entry »

Share