C++: Smart pointers, part 5: weak_ptr

This is the last of several posts I wrote related to smart pointers:

  1. Smart pointers
  2. unique_ptr
  3. More on unique_ptr
  4. shared_ptr
  5. weak_ptr

In modern C++ applications (C++11 and later), you can replace almost all your naked pointers to shared_ptr and unique_ptr in order to have automatic resource administration in a deterministic way so you will not need (almost, again) to release the memory manually.

The “almost” means that there is one scenario where the smart pointers, specifically, the shared_ptr instances, will not work: When you have circular references. In this scenario, since every shared_ptr is pointing to the other one, the memory will never be released.

Continue reading

C++11: Perfect forwarding

Consider this function template invoke that invokes the function/functor/lambda expression passed as argument passing it the two extra arguments given:

#include <iostream>
#include <string>

using namespace std;

void sum(int a, int b)
{
    cout << a + b << endl;
}

void concat(const string& a, const string& b)
{
    cout << a + b << endl;
}

template <typename PROC, typename A, typename B>
void invoke(PROC p, const A& a, const B& b)
{
    p(a, b);
}

int main()
{
    invoke(sum, 10, 20);
    invoke(concat, "Hello ", "world");
    return 0;
}

Nice, it works as expected and the result is:

30
Hello world

Continue reading

C++: Smart pointers, part 4: shared_ptr

This is the fourth post of several posts I wrote related to smart pointers:

  1. Smart pointers
  2. unique_ptr
  3. More on unique_ptr
  4. shared_ptr
  5. weak_ptr

As I mentioned in other posts, C++11 brings a new set of smart pointers into C++. The most useful smart pointer is shared_ptr: Its memory management policy consists in counting the number of shared_ptr instances that refer to the same object in the heap.

Continue reading

C++: Smart pointers, part 3: More on unique_ptr

This is the third post of several posts I wrote related to smart pointers:

  1. Smart pointers
  2. unique_ptr
  3. More on unique_ptr
  4. shared_ptr
  5. weak_ptr

Ok, here I am going to write about two other features that unique_ptr has that I did not mention in my last post.

unique_ptr default behavior consists on take ownership of a pointer created with new and that would normally be released with delete.

Continue reading

C++11: Smart Pointers, part 2: unique_ptr

This is the second post of several posts I wrote related to smart pointers:

  1. Smart pointers
  2. unique_ptr
  3. More on unique_ptr
  4. shared_ptr
  5. weak_ptr

C++11 ships with a set of out-of-the-box smart pointers that help us to manage the memory easily.

One of those smart pointers is the unique_ptr.

Continue reading

C++11: std::future and std::async

C++11 introduces support for asynchronous calls in a very easy way.

An asynchronous call is a method invocation that will be executed in a separate thread (or core or processor); so, the caller of the method does not wait for the result of the execution and continue doing what is next; in this way, the compiler/processor/operating system can optimise the execution of the program and execute several routines at the same time (given the now common multicore systems we all have at home and in our pockets!). The standard library provides the mechanisms to perform those asynchronous calls and store the results until the caller will actually need them.

Continue reading

C++11: std::thread

The standard library that ships with the new C++11 contains a set of classes to use threads. Before this, we needed to use the OS specific thread facilities each OS provides making our programs hard to port to other platforms.

Anyway, as today (November 16th, 2012), I tried threads using g++ 4.7 in Linux, Windows (through mingw), Mac and NetBSD and I just had success in Linux, Windows and Mac do not implement the thread features and NetBSD misses some details on the implementation (the this_thread::sleep_for() method, for example). Microsoft Visual Studio 2012 ships with good thread support.

To define a thread, we need to use the template class std::thread and we need to pass it a function pointer, a lambda expression or a functor. Look at this example:

Continue reading

C++11: reference_wrapper

Look at this piece of code:

#include <iostream>
#include <functional>

using namespace std;
using namespace std::placeholders;

void add(int a, int b, int& r)
{
	r = a + b;
}

int main()
{
	int result = 0;
	
	auto f = bind(add, _1, 20, result);
	
	f(80);
	
	cout << result << endl;
	return 0;
}

Continue reading

C++11: enable_if

std::enable_if is another feature taken from the Boost C++ library that now ships with every C++11 compliant compiler.

As its name says, the template struct enable_if, enables a function only if a condition (passed as a type trait) is true; otherwise, the function is undefined. In this way, you can declare several “overloads” of a method and enable or disable them depending on some requirements you need. The nice part of this is that the disabled functions will not be part of your binary code because the compiler simply will ignore them.

Continue reading

C++: SFINAE

Say you have this piece of code:

template <typename T>
void show(typename T::iterator x, typename T::iterator y)
{
	for (; x != y; ++x) cout << *x << endl;
}

int main()
{
	show<int>(16, 18);
}

Continue reading

Mercurial: StatHG is alive!

A bunch of colleagues and friends were very busy developing this very nice tool that lets you get nice reports from Mercurial. Taken from the project web page:

StatHg generates statistical report graphs from the Mercurial activity log. The generated report is independent of the application and can be freely transferred or even published using a web server.

Continue reading

C++11: std::function and std::bind

std::function and std::bind were born inside the Boost C++ Library, but they were incorporated into the new C++11 standard.

std::function is a STL template class that provides a very convenient wrapper to a simple function, to a functor or to a lambda expression.

Continue reading

C++11: unordered maps

The STL ships with a sorted map template class that is commonly implemented as a balanced binary tree.

The good thing on this is the fast search average time ( O(log2N) if implemented as a balanced binary tree, where N is the number of elements added into the map) and that when the map is iterated, the elements are retrieved following an established order.

C++11 introduces an unordered map implemented as a hash table. The good thing on this is the constant access time for each element ( O(1) ) but the bad things are that the elements are not retrieved in order and the memory print of the whole container can (I am just speculating here) be greater that the map’s one.

Continue reading

C++: Smart pointers, part 1

This is the first of several posts I wrote related to smart pointers:

  1. Smart pointers
  2. unique_ptr
  3. More on unique_ptr
  4. shared_ptr
  5. weak_ptr

Memory management in C is too error prone because keeping track of each bunch of bytes allocated and deallocated can be really confusing and stressing.

Although C++ has the same manual memory management than C, it provides us some additional features that let us to do this management easier:

  • When an object is instantiated in the stack (e.g. Object o;); the C++ runtime ensure the destructor of such object is invoked when the object goes out of scope (the end of the enclosing block is reached, a premature ‘return’ is found or an exception is thrown); thus, releasing all memory and resources allocated for such object.
  • (Ab)using the feature of operator overloading, we can create classes that simulate the behavior of the pointers. Such classes are called: Smart pointers.

Continue reading

Project X

This is an amazing video created by a friend.

Enjoy it!

Continue reading

C++: Primitive types

A primitive type is a data type where the values that it can represent have a very simple nature (a number, a character or a truth-value); the primitive types are the most basic building blocks for any programming language and are the base for more complex data types. These are the primitive types available in C++:

Continue reading

C++11: C++-style listener list

Consider you want to create a class where you can register a set of listeners to be notified when something occurs. For example, this is a class that performs some task and you want to be notified when the task has been completely executed. See this code in Java:
Continue reading

C++11: Variadic templates (functions)

A very interesting C++0x feature are the “variadic templates” that, in short, are template classes and functions with a variable number of parameterized types. They can be useful to do several things, for example:
Continue reading

C++11: nullptr

In C and C++ we use the preprocessor macro NULL to say a pointer is not pointing to anywhere right now.

The problem with NULL is that underneath it is just a plain 0.

Consider the problem looking at this code excerpt:
Continue reading

C++11: Range-based for loop

In C++03, if I have a vector and want to show its elements, I could do something like this:

template <typename T>
void show(const T& x)
{
	for (typename T::const_iterator i = x.begin(); i != x.end(); i++)
		cout << *i << endl;
}

Continue reading

Follow

Get every new post delivered to your Inbox.