Qt Creator error: Cannot retrieve debugging output

Qt Creator allows you to open and run multiple instances of Qt Creator at the same time. But there is a small glitch. If you are running multiple instances of Qt Creator, only the first instance displays the console output in the Application output console. The second instance would complain with the following error message:

Cannot retrieve debugging output

Fix for this is to close the second instance or open the project you want to edit and debug in the first instance.

C: Initialize multiple variables in same declaration statement

First thing first, never initialize nor declare multiple variables on the same line. It makes things very difficult to understand. But if you have to, this post will help you.

Initializing multiple variables in same line like this:

int p, q = 10;

is ambiguous because it is hard to understand if only q is initialized to 10 or if p is also initialized to 10. Of course, in this case only q is initialized to 10. To avoid the ambiguity, each initialization can be done in its own line.

int p;
int q = 10;

Also, try to initialize automatic variables (especially pointer variables) when they are declared.

C: declaring multipe pointer variables in same declaration statement

First thing first, never declare multiple pointer variables in same declaration statement. Don’t mix declaration of pointer and non-pointer variables in same line. Following this will save you a lot of debugging time in the future.

But in case, you are forced do it or you are debugging code written by somebody else, this short post can help you.

What does this code really mean?

int* c, d;

It is clear that c is a pointer to integer. But what about d? Is it integer or pointer to integer? Ofcourse, it is integer not a pointer to integer. Using declaration as above is very ambigious. Avoid it any cost. Instead, declare them on their own statements.

int* c;
int d;

Much clear. Isn’t it?

It is also better to follow this rule when all variables are pointers. Also, I prefer to put the star next to varaible name instead of the variable type.

int *p, *q;

is more intuitive than

int* p, *q;

C++: Initializing parent class member variables in derived class constructor

Usually we initialize member variables in constructor using initialization list.

class Base {
public:
    int i;
    explicit Base(int _i) : i(_i) {
        //other initialization code
    }
};

But we cannot initialize the parent class public or protected member variable in derived class constructor’s initialization list.

class Derived: public Base {
public:
  int j;
  Derived(int _i, int _j) : i(_i), j(_j) {

  }
};

The above code will produce the following error:

par_var_init.cpp: In constructor ‘Derived::Derived(int, int)’:
par_var_init.cpp:16:28: error: class ‘Derived’ does not have any field named ‘i’
Derived(int _i, int _j) : i(_i), j(_j) {

Using parent constructor

The correct way to do this is by calling the base class constructor to initialize its variables.

class Derived: public Base {
public:
  int j;
  Derived(int _i, int _j) : Base(i), j(_j) {

  }
};

Initializing parent’s member variables in derived class constructor’s body

It is possible to initialize parent’s member variables in derived constructor’s body.

class Derived: public Base {
public:
  int j;
  Derived(int _i, int _j) : j(_j) {
    i = _i;
  }
};

Note: the following approach is wrong!

class Derived: public Base {
public:
  int i;
  int j;
  Derived(int _i, int _j) : i(_i), j(_j) {
  }
};

This will create a new variable in derived class called i that is separate from Base::i.

C++11 regex using g++

Boost regex has been accepted into C++11. So, I decided to give it a try using g++.

#include<iostream>
#include<string>
#include<regex>

using namespace std;

int main() {
        string str("2 a\n3 b\n4 c\n5 d\n6 c");
        regex r("[0-9]");

        regex_iterator<string::iterator> start(str.begin(), str.end(), r);
        regex_iterator<string::iterator> end;

        while(start != end) {
                cout << start->str() << endl;
                ++start;
        }
}

I was surprised to get a big fat link-time error:

/tmp/cc80j8Z8.o: In function `main':
regex1.cpp:(.text+0x133): undefined reference to `std::regex_iterator<__gnu_cxx::__normal_iterator<char*, std::string>, char, std::regex_traits >::regex_iterator(__gnu_cxx::__normal_iterator<char*, std::string>, __gnu_cxx::__normal_iterator<char*, std::string>, std::basic_regex<char, std::regex_traits > const&, std::bitset)’
regex1.cpp:(.text+0x13f): undefined reference to `std::regex_iterator<__gnu_cxx::__normal_iterator<char*, std::string>, char, std::regex_traits >::regex_iterator()’
regex1.cpp:(.text+0x150): undefined reference to `std::regex_iterator<__gnu_cxx::__normal_iterator<char*, std::string>, char, std::regex_traits >::operator->()’
regex1.cpp:(.text+0x1a9): undefined reference to `std::regex_iterator<__gnu_cxx::__normal_iterator<char*, std::string>, char, std::regex_traits >::operator++()’
regex1.cpp:(.text+0x1bf): undefined reference to `std::regex_iterator<__gnu_cxx::__normal_iterator<char*, std::string>, char, std::regex_traits >::operator!=(std::regex_iterator<__gnu_cxx::__normal_iterator<char*, std::string>, char, std::regex_traits > const&)’
collect2: error: ld returned 1 exit status

Seems like gcc 4.8.2, delivered by my distribution doesn’t support regex yet. So, we are forced to use Boost regex for now. Or use g++ 4.9.0 instead, which has regex implemented. To install the latest g++ release, execute the following command in the terminal:

sudo add-apt-repository ppa:ubuntu-toolchain-r/test
sudo apt-get update
sudo apt-get install g++-4.9

To compile the code with g++4.9:

g++-4.9 --std=c++11 regex1.cpp -o regex1

C++ collection: how are objects stored

Note: In this article, we will use vectors for demonstration. But the same applies for all collections in C++.

Have you wondered, how C++ STL stores objects in its storage and its consequences? That is exactly what we are going to discuss today. When you insert, push_back, assign, etc an object into C++ STL collections, the default behavior is C++ copies the object using copy constructor and stores the newly created object. One obvious consequence of this is that, changes made to the original object inserted has no effect on the object stored.

Output:

Original before modification: 5
Original after modification: 6
Stored after modification: 5

Another consequence and the most important consequence occurs when the class has dynamically allocated members. The default copy constructor provided by C++ does a shallow copy of these pointers. This will lead to segmentation faults when the objects are being destructed.

Output:

copy constructor Data(const Data &d)
1
2
3
4
5

destructor
*** Error in `./copy_problems': double free or corruption (fasttop): 0x00000000021f4010 ***
Aborted (core dumped)

So, how do we overcome this issue? Below we will discuss various ways in which this problem can be fixed.

Vector of pointers to objects

One of the easiest way to achieve this is by creating a vector of pointers to objects instead of vector of objects. This makes sure that the object stored is the object inserted.

It should be noted that automatic variables created on stack should not be stored this way, if the vector could be passed out of the function. This is because when the function frame is unrolled, the object allocated on the stack is destroyed.

Note: In C++, vector of reference to objects is not possible.

Vector of shared_ptr to objects

As you might have noticed, the previous solution has two problems:

  • Objects should be allocated in heap
  • The destruction of the object is left to the developer. This could lead to serious problems!

The obvious solution to fix the problems with previous solution is to use shared_ptr instead of raw pointers. shared_ptr keeps reference counts and destructs the object when there are no references left to the object. This works well because methods that remove elements from vector calls the destructor of the element being removed.

Use move semantics instead of copy semantics

C++ STL collections allow the use of move semantics instead of copy semantics to clone the object being inserted. I will dedicate an entire post for this solution.

C++11: How to create cyclic dependencies with shared_ptr and how to avoid them

C++ smart pointers are god send to C++ programmers. It avoids dealing with raw pointers and takes care of resource deallocation when the pointed “whatever” goes out of scope. All great. But there does exist some pitfalls and we should be vary of them. One such pitfalls is cyclic dependency when using shared_ptr. Cyclic dependency occurs when there is self-reference either in its own member or through the member of a member or through the member of a member of a member…. ok. I will stop. You get it :P.

Cyclic dependency

Cyclic dependency

Creating cyclic dependency

First we will see how we can create a cyclic dependency. Then we will see how to avoid them by using weak pointers.

Here we show two ways to create cyclic dependency:

  1. Cyclic dependency due to a self-referencing member
  2. Cyclic dependency due to a member of a member referencing this

Case 1

When ptr is created, its count is initialised to 1. When it is assigned to ptr->a, its count is incremented by 1 to 2. What this means is that ptr will not be deleted until both ptr and ptr->a are reset. But there is no way for that to happen. When ptr goes out of scope, the count will be decremented by 1 to 1. Since the count is not 0, ptr will not be deleted. ptr->x will not be reset until ptr is deleted. ptr will not be deleted until ptr->x is reset.
So shortly: ptr cannot be released because ptr->x will not be reset until ptr is reset.

Case 2

When x is created, its count is initialised to 1. When it is assigned to x->b->a, its count is incremented by 1 to 2. What this means is that x will not be deleted until both x and x->b->a are reset. But there is no way for that to happen. When x goes out of scope, the count will be decremented by 1 to 1. Since the count is not 0, x will not be deleted. Since x is not deleted, x->b will be not be deleted. Since x->b will not be deleted, x->b->a will not be deleted. If x->b->a will not be deleted, x will not be deleted. Go back 3 lines and start reading again and again and again :P.
So shortly: x(and hence x->b) will not be released because x->b->a will not be reset until x is reset.

Solving cyclic dependency using weak_ptr

Changing the self-referencing member a of ClassA to weak_ptr fixes the cyclic dependency problem in case 1.
Changing the member a of ClassB to weak_ptr fixes the cyclic dependency problem in case 2.

Courtesy: Stackoverflow

C++: vector of arrays

In C++ arrays cannot be stored in vectors. This restriction is due to the fact that arrays cannot be copy constructed or assigned. For example, this won’t compile in c++

To work around this limitation, c++11 has introduced a new container called std::array. std::array is just a template class that encapsulates a static array. It cannot be resized and its size should be know at compile time. Here is a small example on how to create a vector of arrays.

c++: dynamic_cast

dynamic_cast is used to cast a pointer of a polymorphic objects(pointer to base or derived classes) up or down the inheritance hierarchy. It is more safe than reinterpret_cast because it performs a type check at run time. dynamic_cast uses run time information to figure out if the classes are polymorphically related. For this reason, dynamic_cast requires that RTTI is enabled in the compiler. This also means that the pointer being casted should be polymorphic(has virtual functions). If the type of the pointer being casted is not polymorphic, a compile time error is thrown.

Lets consider these three classes(1 base class and two derived classes) for illustration:

To cast a pointer of Base object to a pointer of Derived object:

To cast a pointer of Derived object to a pointer of Base object:

dynamic_cast assures type safety by returning a NULL pointer when the casted pointer cannot be safely converted to destination type. Hence, the returned pointer should be tested for NULL before use.

Note: If you don’t want to have any virtual functions, the best thing to do is to make the destructor virtual.