Interruption At Work Created A Mishap

INTERRUPTIONS AT WORK is a frequent occurrence but generally its not a big problem. This time however the unavoidable loss of focus on what you was doing before, gave an unpleasant surprise.

I was adding some new functionality and had just written the following:

switch (state) {
    case Step3:
        configuration.length = 10;
        break;
}

Next I added a line to specify the configuration data on index zero. With the intention of doing this for the remaining nine data indexes, I copy-pasted the first line and incremented the index.

switch (state) {
    case ConfigureTask:
        configuration.data[0] = 
        configuration.data[1] = 
        configuration.length = 10;
        break;
}

But this was at the exact moment a colleague asked a question. To figure out the answer I had to browse around in the same file I was just editing. Not finding the complete answer there, the hunt led on to opening a bunch of other files. Eventually the situation evolved to a discussion using a white-board.

Now, even though the above code is incomplete, it compiles to perfectly valid code!. What the above code does is to initialize configuration.data[0], configuration.data[1] and configuration.length to 10. Naturally this behavior was never the desired behavior for that code…

Later, returning to my workstation, I had completely forgotten about the unfinished implementation I worked on before. In my mind it was already done and I proceeded on other things that would eventually allow me to run some basic tests for the new implementations. The nature of the code is to delegate a state dependent number of black-box data to a task. The receiving task is found by peeking into the first byte of the black-box data (configuration.data[0]). Unfortunately ’10’ is a perfect match for the first task to be configured. So when unit-testing, at first everything seemed to be okay.

Later some strange behavior appeared, for which I could find no good reasons. Eventually I found the faulting situation in great dismay.

This kind of logic errors is the kind that can become extremely difficult to find, and I’ve learned my lesson: if leaving in the middle of writing some source code, be sure to quickly add some non-code that will not compile.

Numbers To Strings And Back Again – Standard C++ vs. Boost

CONVERTING NUMBERS TO strings or the opposite of converting strings to numbers, is an operation that is far from as trivial as one would expect from such an obvious task – at least when it comes to C++ programming using standard libraries. The converting can be performed by the iostringstream classes in the standard library. When searching Google for the C++ way of converting between numbers and streams, the stringstream library classes appears not to be the that well known, and especially its features of the number and string operations seems generally to be unknown by many.

The stringstream offers a large range of manipulating stream data, although if used for e.g. special formatted textual output, the implementation steps tends to be somewhat more cumbersome than the old printf family.

The example below takes a few more lines that doing e.g. a atoi or snprintf kind of operation, but depending on the situation, simple conversion scenarios do not require many lines of code.

Standard Input / Output Streams Library

The main function is extracted here, just not to obfuscate the picture of the actual converting. Note that stringstream is defined in the <sstream> header.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <sstream>  // stringstream
 
// Prototypes
void Std_StringToInteger();
void Std_IntegerToString();
 
int main(int argc, char *argv[])
{
  std::cout << "Std_StringToInteger:" << std::endl;
  Std_StringToInteger();
  std::cout << "Std_IntegerToString:" << std::endl;
  Std_IntegerToString();
}

The function below handles conversion from strings to integers. First a simple conversion is done, then followed by an example of testing whether the conversion operation was a success. Last is shown how to enable exceptions on conversion errors.

15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
void Std_StringToInteger()
{
  std::string str = "1976";
  int val;
 
  // Load stringstream with text to convert
  std::istringstream is(str);
  // Convert by streaming to integer
  is >> val;
  std::cout << "  Val: " << val << std::endl;
 
  // Clear stream for another input
  is.clear();
 
  // Load stream with a non numeric convertible data
  is.str("Monzool.net");
  is >> val;
 
  // Test if conversion failed
  if (is.fail())
    std::cout << "  Conversion failed!" << std::endl;
 
  // Enable exceptions on conversion errors
  try
  {
    // Set failures to be thrown as exceptions
    is.exceptions(std::istringstream::eofbit  |
                  std::istringstream::failbit |
                  std::istringstream::badbit);
  }
  catch(std::istringstream::failure& e)
  {
    std::cout << "  Exception: " << e.what() << std::endl;
    std::cout << "  Conversion failed!" << std::endl;
  }
}

As the naming stringstream indicates, input and output is done by streaming measures. If not quite confident on stream directions, think of how functions cout and cin is used. Using stringstream is no different.

Last function is for converting from numbers to strings.

51
52
53
54
55
56
57
58
59
60
void Std_IntegerToString()
{
  int val = 1976;
 
  // Create empty stringstream for number to convert
  std::ostringstream os("");
  // Convert by streaming integer
  os << val;
  std::cout << "  Str: " <<  os.str() << std::endl;
}

Boost lexical_cast

To put it simple: when dealing with libraries for converting between numbers and strings the Boost library smokes the standard C++ library ditto.

The conversion features of Boost is located in the lexical_cast library and is embedded by including the lexical_cast.hpp file (most Boost libraries are implemented in header files and can be embedded by including the appropriate hpp file.).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <boost/lexical_cast.hpp>
 
// Prototypes
void Boost_StringToInteger();
void Boost_IntegerToString();
 
int main(int argc, char *argv[])
{
  std::cout << "Boost_StringToInteger:" << std::endl;
  Boost_StringToInteger();
  std::cout << "Boost_IntegerToString:" << std::endl;
  Boost_IntegerToString();
}

Instead of using streaming functionality, Boost has chosen a much more obvious concept. Boost has added the functionality of simply casting between numbers and strings. Casting functions are already a familiar concept in C++, like casting between data types using static_cast or manipulating const’ness with const_cast.

The lexical_cast template function makes converting from string to integer trivial. The example below also shows how to handle conversion errors by exception handling.

15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
void Boost_StringToInteger()
{
  std::string str = "1976";
  // Cast string to integer
  int val = boost::lexical_cast<int>(str);
  std::cout << "  Val: " << val << std::endl;
 
  // Load string with non numeric convertible data
  str = "Monzool.net";
  try
  {
    // Non convertible values throws exceptions
    val = boost::lexical_cast<int>(str);
  }
  catch (boost::bad_lexical_cast &e)
  {
    std::cout << "  Exception: " << e.what() << std::endl;
    std::cout << "  Conversion failed!" << std::endl;
  }
}

Converting the other way from integer to string is just as trivial.

35
36
37
38
39
40
41
void Boost_IntegerToString()
{
  int val = 1976;
  // Cast integer to string
  std::string str = boost::lexical_cast<std::string>(val);
  std::cout << "  Str: " << str << std::endl;
}

When it comes to simple conversion between numbers and strings, Boost is far superior in simplicity. However note that the design goals have also been very different for the two libraries. The C++ Standard Input/Output Streams Library has been designed for flexibility. And flexible it is indeed, but sadly this side effects to complicating its usage even for obvious tasks that ought to be trivial to perform.

C++ Function Hidden, Not Overloaded Nor Overridden

THE C++ INHERITANCE model can be unintuitive some times – or perhaps more correctly, its easy to get tricked by C++ in some circumstances.

When having an existing code base the need sometimes comes up, that an often used class is needed with a few additional features. Not to mess with any of existing code, a new class is created deriving from the original class. No functionality can be extended without breaking any existing code using the original code – sweet. But care is advised, or one might inadvertently step on a landmine.

The example below is a snippet from a boat class that provides a member for setting the speed of the boat. Positive values indicates forward sailing while negative values is backward sailing. Given the task of producing a super fast race boat a new class FastBoat is derived so that unrealistically high speeds can be executed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Boat
{
  public:
          virtual ~Boat() {}
          virtual void Speed(int speed)
          {
            std::cout << "Speed of boat: " << speed << std::endl;
          }
};
 
class FastBoat: public Boat
{
  public:
          virtual ~FastBoat() {}
 
          virtual void Speed(unsigned int speed)
          {
            std::cout << "Speed of fast boat: " << speed << std::endl;
          }
};
 
 
int main(int argc, char *argv[])
{
  std::cout << "Maneuvring the boat\n" << std::endl;
 
  const unsigned int ForwardKnots  = 22;
  const int          BackwardKnots = -3;
 
  FastBoat fastBoat;
  fastBoat.Speed(ForwardKnots);
  fastBoat.Speed(BackwardKnots);
 
  return EXIT_SUCCESS;
}

Glancing at the code one might be convinced that all is fine an dandy. Setting unsigned speeds on a FastBoat would trigger the FastBoat object, while signed speeds would propagate to the base Boat object.


This, however, is the output produced by the example code:

Speed of fast boat: 22
Speed of fast boat: 4294967293

Wanting to reverse the boat at mere 3 knots, the boat is sent forward at cartoon-fast speed. So what just happened?. Well, the Boat::Speed function was not called, and instead the BackwardKnots value was casted to fit the FastBoat::Speed function. This is because function overload resolution does not cross inheritance boundaries – that is, not by default. For the above code to work as intended, the hidden function from the base class must be brought into scope.

11
12
13
14
15
16
17
18
19
20
class FastBoat: public Boat
{
  public:
          virtual ~FastBoat() {}
          using Boat::Speed;    // Bring Boat::Speed function into scope
          virtual void Speed(unsigned int speed)
          {
            std::cout << "Speed of fast boat: " << speed << std::endl;
          }
};

Daring another attempt to test the program, the result now is as intended.

Speed of fast boat: 22
Speed of fast boat: -3

The using directive has brought the base class function into the namespace scope and is thus called correctly as it is no longer hidden.

Its an easy mistake to make and thats surely why other languages (e.g. D and C#) have introduced keyword for explicitly specifying what action intended. If using GCC compiling with the -Woverloaded-virtual options is recommended for catching these kind of mistakes.

C++ Contructor/Destructor Call Order

WHEN BEGINNING C++ programming I’ve experienced people to have trouble remembering the correct construction and destruction call order. Personally I conquered this using a common memory technique – creating a story.

Here are two stories that might help in remembering. The stories might seem quite long, but don’t fear, it’s not necessary to remember the stories word by word. Btw. the storytelling does not fly 100[%], but they are good enough… at least for me ;-)

Story #1: The Skyscraper

The skyscraper story is exemplified from this simple class structure:

1
2
3
4
5
6
7
8
9
class Base
{
  Base() { cout << "Base" << endl; }
};
 
class Derived : public Base
{
  Derived() { cout << "Derived" << endl; }
};

A couple of prerequisites are necessary:

1) Imagine the UML class diagram of the above turned upside down.

Class diagram turned upside down

2) Imagine that the each class in the upside down diagram represents a floor in a skyscraper.

Class diagram is a building

The Base is the foundation and all Derived objects are floors that builds upon that foundation.

Construction
Start constructing here --->

So to construct a skyscraper the building process must be Base first, then Derived next, as buildings (usually) are build from bottom and upwards.

When destructing the destruction order is the same as dismantling a building, top to bottom.

Start destructing here --->
Destruction

So what about the special case of destruction when the object is polymorphic?

When allocated is looks like its a building with only a base level; even though we know its a building two storages high.

10
Base* pBase = new Derived;

The problem here is that the demolition team only have access to the base level and when destroying the building, disaster will happen…

11
delete pBase;

As the building is two storages high, it will collapse when the supporting foundation is removed first (allegorizing a bad situation as the Derived object would not get destroyed when only deleting the base object).

So how to fix this situation? You provide the demolition team with an elevator. The “elevator” is a special demolition model called virtual.

12
13
14
15
16
class Base
{
  Base() { cout << "Base" << endl; }
  virtual ~Base() { cout << "~Base" << endl; }  // Virtual destructor
};

As the building is equipped with an elevator the demolition team can escalate to the top of the building and begin the destruction from top to bottom and get everything removed properly.

Story #2: File Manipulation

The second story relate the base/derived situation to file contents manipulation.

A file must be opened before it can be closed, and if opened it must be closed again at some point. Thus it make sense to create a class that opens the file in the constructor, and closes the file again in the destructor.

1
2
3
4
5
class FileAccess
{
  FileAccess() { cout << "Open file..." << endl; }
  ~FileAccess() { cout << "Close file..." << endl; }
};

Read and write operations are similar functionality (transfer data, but in opposite direction) and thus it makes sense to collect this functionality in one class. As the goal is to modify the contents of a file, the reading of the existing file content can be placed in the constructor, and writing of the modified content in the destructor.

6
7
8
9
10
11
12
class FileManipulate
{
  FileManipulate() { cout << "Read from file..." << endl; }
  ~FileManipulate() { cout << "Write to file..." << endl; }
 
  // Content manipulation functions follows here...
};

Two classes are now at hand. One that opens and closes a file, and one that reads the contents of the file and writes it back to the file.

A prerequisite of reading from a file or writing to a file is that the file is open. Therefore the basic but essential functionality of opening and closing is made the base class (FileAccess). The more advanced and flexible functionality of reading and writing is then made in the derived class (FileManipulate).

11
12
13
14
15
16
17
18
19
20
21
class Base /* FileAccess */
{
  Base() { cout << "Open file..." << endl; }
  ~Base() { cout << "Close file..." << endl; }
};
 
class Derived /* FileManipulate */ : public Base /* FileAccess */
{
  Derived() { cout << "Read from file..." << endl; }
  ~Derived() { cout << "Write to file..." << endl; }
};

Thus every time an object is created of the derived class for modifying a files contents, it automagically also inherits the capabilities of opening and closing files. And as a file cannot be read from before the file is opened, it can be remembered that the base constructor must be called before the derived constructor. Equally it cannot be written to the file after the file is closed, thus is can be remembered that the derived destructor is called before the base destructor.

Placement new

REPLACEMENT NEW CAME to mind, when working on a C++ project of mine. In this project some large objects of short lifetime led to a concerns about memory fragmentation on the targeted embedded platform that have only sparse memory ressources. The life cycle of the objects was to create an object, then fill the large data member structures, store data for a while until time for transmitting the data and terminate the object. The object data where always different so they could not be reused, and the lifetime of each object was inditerminable. However it was certain that only a known maximum amount of objects would exist at the same time.

This senario made me think of a rarely used memory allocation functionality called placement new that would handle the above concerns perfectly. With this variant of new you allocate a memory pool of fixed memory address and size, from which allocations can be made from. This way placement new allows reuse of the same memory again and again and thus containing any memory fragmentation within the disposable memory pool.

Below is a simple example of how to use the placement new functionality.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <iostream>
#include <iomanip>
#include <new>
#include <stdio.h>
using namespace std;
 
class C
{
  public:
            C() : data(0x11) { ; }
            ~C() { data = 0x22; }
 
            char data;
};
 
int main(int argc, char *argv[])
{
  const int PoolItems = 6;
  const int PoolSize  = PoolItems * sizeof(C);
 
  // Allocate a memory pool
  char *pool = new char[PoolSize];
  memset(pool, 0x00, PoolSize);
 
  // Create some pointers to access pooled objects
  C *pC[PoolItems] = { 0 };
 
  // Allotate objects at "arbitary" addresses in the pool
  pC[1] = new (pool + sizeof(C)*1) C;
  pC[4] = new (pool + sizeof(C)*4) C;
 
  // Display constructed data
  for (int i = 0; i < PoolSize; i++)
    cout << setfill('0') << setw(2) << std::hex << (int)pool[i] << " ";
  cout << endl;
 
  // Explicit destruction of objects in pool
  for (int i = 0; i < PoolItems; i++)
  {
    if (pC[i] != NULL)
    {
      pC[i]->~C();  // Explicit destructor call
      pC[i] = NULL;
    }
  }
 
  // Display destructed data
  for (int i = 0; i < PoolSize; i++)
    cout << setfill('0') << setw(2) << std::hex << (int)pool[i] << " ";
  cout << endl;
 
  // Release memory in pool
  delete [] pool;
  pool = NULL;
 
  return EXIT_SUCCESS;
}

Explanation: First a memory pool is created that fits a fixed amount of the designated class objects. Two object are then created within pool slots 1 and 4. The simple byte sized class C has a contructor initialization of the member data.

The first printing of the pool will display the following contents:

00 11 00 00 11 00

This indicates that two slots are allocated with objects of the class C.

Destructing the objects are done by calling the destructor explicitly, NOT by normal delete action (as the memory pool original was created as a char array, the memory it occupies is tagged as a char array that must be deleted the approriate array delete operation). After destruction, the pool contents is displayed again, and it is seen that the same memory has been rewritten by the destructor assigning:

00 22 00 00 22 00

Finally the memory pool is deleted and the memory is released.

Copyright © All Rights Reserved · Green Hope Theme by Sivan & schiy · Proudly powered by WordPress