Archive for the ‘c++’ Category

Inheritance misunderstood

Thursday, May 27th, 2010

In C++ inheritance is not for code reuse. Full stop. Think subtyping. Think interface. Think substitution. Think specification. Learn about LSP – Liskov Substitution Principle. Never ever think reuse.

I’m amazed, shamefully, how often I forget about it and I drift away thinking how to save on keyboard use and typing.

Boost.Geometry blog

Sunday, March 14th, 2010

Boost Geometry (aka Generic Geometry Library, GGL)It’s been a month since Barend Gehrels launched blog dedicated to development of Boost.Geometry library which is also known of its former name as Generic Geometry Library or shortly GGL.

Here I go we a bit delayed announcement: http://barendgehrels.blogspot.com

Boost.Geometry and macros made by Apple

Wednesday, March 10th, 2010

Boost Geometry (aka Generic Geometry Library, GGL)I have no pleasure continuing my macros are evil tales but the life of C++ programmer eagerly wants to writes add another chapter to the story. Today, it’s time to rant on Apple and its XCode.

One of Boost Geometry (aka GGL) users, Mark, reported that he can not compile his program using the library with GNU C++ compiler from XCode. The compiler throws mysterious complain of a very low-level nature of C++ programming language:

Expected unqualified-id before 'do' in
/usr/local/include/boost_1_42_0/boost/geometry/geometries/concepts/check.hpp

Thanks to follow-up by Stjepan we quickly know who to blame for that. It is XCode header AssertMacros.h. It even might be one of public headers from development package of XNU, the Mac OS X kernel, what’s even more fun.

What actually happens that causes the problem?

Boost Geometry defines function template for concept checking:

template <typename Geometry>
inline void check()
{
    detail::checker<Geometry, boost::is_const<Geometry>::type::value> c;
    boost::ignore_unused_variable_warning(c);
}

Apple XCode defines macro using exactly the same name as the function check. The C++ preprocessor, which operates before compiler, substitutes the name check with content of the macro. For the Boost Geometry function check it means that a pile of garbage is injected in place were the function name is expected:

template <typename Geometry>
inline void do { if ( __builtin_expect(!(), 0) ) { DebugAssert('?*?*',
0, "Third Party Client" ": " "", 0, 0, "/usr/local/include/boost/
geometry/geometries/concepts/check.hpp", 181, (void*)0); } } while ( 0 )
{
     detail::checker::type::value> c;
     boost::ignore_unused_variable_warning(c);
}

Obviously, it makes compiler to give up to instantiate the check function from the template and to compile it properly.

C/C++ macros are evil, however, not by design but by insanity of programmers. Every macro defined in a public C/C++ header, should be defined using as unique as possible, but still usable name. I wish Apple folks designed their C/C++ macros as unique as they make their hardware products, even if made in China eventually. This particular macro that caused the problems discussed here, could be named to APPLE_XNU_CHECK and life would be easier. Or, given the fact that almost 3000 files using these identifiers live in Boost C++ Libraries only, I probably should say: life would be more productive, efficient and cheaper.

By the way, it’s a known problem @ Boost and it looks Boost Folks are trying to figure out best solution. See ticket #2115 – Avoid bad Apple macros.

…to be continued

Const-correctness schizophrenia in GDAL

Thursday, March 4th, 2010

Const-correctness rants are quite common topic of chats on #gdal IRC channel. Some of the pearls I’ve got printed in to my mind:

A: The lesson is I ought to get things right the first time.
B: The issue with const method is that if you want to add lazy loading later, it can cause problems
C: GDAL is rather painful to use with const correct code, unfortunately :(
B: The solution is obvious: don’t write const correct code

Who’s right then, A or B?

I recall another motto from #gdal channel that sounds like “when unsure, do nothing” which has the following rationale:

especially when I realize afterwards that I’ve f**cked things because I neglected to follow the motto

Remembering these recommendations, it’s pretty clear why the const-mess in GDAL has happened. I’d conclude paraphrasing the motto this way:

I’ve f**cked things because I neglected to make a decision.

Now, poor GDAL beginner deadpickle, trying to find out (it’s me the evil) why compiler complains about his not-that-bad-written code, wandered to find and ask C gurus @ comp.lang.c and got the problem explained by Malcolm who wrote:

The problem is that, when C was first developed, there was no const keyword. So strings literal, which are constant, had to be non-const for backwards compatibility. This means that lots of programmers get lazy and omit the const, even from functions which don’t modify their string arguments. (There are also some subtle problems with const which means that this isn’t always a case of pure laziness). So a sort of solution is to discard the const qualifiers. However this is perpetuating the problem in your own code.

The motto stays in contradiction to a well-known best practice of const correct sooner than later. It’s way easier and cheaper to remove const-correctness once it turns out it does not express properly the actual design and contract than to apply it to existing codebase. Sometimes, the latter is even not possible making things f**cked up twice, in existing code base and in client’s code.

parallel_sort problem fixed

Sunday, February 21st, 2010

My problem with crashing programs using TBB has been solved. Alexey Kukanov replied to my question explaining that because I use TBB 2.1, thus I have to explicitly initialise the task scheduler. Without this initialization, no context (root) for tasks is created, so no tasks possible.

Simply, I was reading latest manual which was generated for TBB 2.2 (available in Ubuntu 10.04), so I missed this legacy requirement. In TBB 2.2 and later, the initialization is optional:

Using task_scheduler_init is optional in Intel? TBB 2.2. By default, Intel? TBB 2.2 automatically creates a task scheduler the first time that a thread uses task scheduling services and destroys it when the last such thread exits.

Correct version of the example program should look as follows:

#include <tbb/task_scheduler_init.h>
#include <tbb/parallel_sort.h>
#include <cmath>
#include <vector>
using namespace tbb;
int main()
{
    task_scheduler_init tbb_init; // automatic

    const int n = 100000;
    std::vector<double> a(n);
    for (int i = 0; i< n; i++)
    {
        a[i] = std::sin(double(i));
    }
    parallel_sort(a.begin(), a.end());
}

parallel_sort crashes on Ubuntu 9.10

Saturday, February 20th, 2010

I’ve started to experiment with the Intel Threading Building Blocks and hit a wall trying to run a very simple example:


#include <tbb/parallel_sort.h>
#include <cmath>
#include <vector>
using namespace tbb;
int main()
{
    const int n = 100000;
    std::vector<double> a(n);
    for (int i = 0; i< n; i++)
    {
        a[i] = std::sin(double(i));
    }
    parallel_sort(a.begin(), a.end());
}
$ g++ -O0 -g -DTBB_USE_DEBUG  -o sort_vector sort_vector.cpp -ltbb
$ gdb ./sort_vector

(gdb) run
Starting program: /home/mloskot/workshop/tbb/parallel_sort/sort_vector
[Thread debugging using libthread_db enabled]

Program received signal SIGSEGV, Segmentation fault.
tbb::task_group_context::init (this=0x7ffffff9c4e0) at ../../src/tbb/task.cpp:3124
3124    ../../src/tbb/task.cpp: No such file or directory.
in ../../src/tbb/task.cpp
(gdb) bt
#0  tbb::task_group_context::init (this=0x7ffffff9c4e0) at ../../src/tbb/task.cpp:3124
#1  0x00000000004013ff in task_group_context (this=0x7ffffff9c4e0, relation_with_parent=tbb::task_group_context::bound)
at /usr/include/tbb/task.h:284
#2  0x0000000000401be4 in tbb::internal::parallel_quick_sort > (begin=0x7ffffff9c6a0,
end=0x7fffffffe120, comp=...) at /usr/include/tbb/parallel_sort.h:155
#3  0x0000000000401b23 in tbb::parallel_sort > (begin=0x7ffffff9c6a0, end=0x7fffffffe120,
comp=...) at /usr/include/tbb/parallel_sort.h:203
#4  0x0000000000401ab3 in tbb::parallel_sort (begin=0x7ffffff9c6a0, end=0x7fffffffe120)
at /usr/include/tbb/parallel_sort.h:219
#5  0x0000000000401363 in main () at sort_vector.cpp:12

It seems like a failure during initialization of worker threads pool or close to it.

I’m using fairly recent version of TBB 2.1 installed from Ubuntu 9.10 packages, but I’m suspicious this may be a problem with this particular binary version. Let’s see what Intel folks will judge parallel_sort example throws segmentation fault. Pity Microsoft PPL does not provide parallel_sort algorithm.

Update: see parallel_sort problem fixed

Preparing Quickbook for Boost.Geometry

Sunday, February 7th, 2010

Generic Geometry Library (GGL)I’ve just started writing Boost.Geometry (aka GGL) documentation in Quickbook. It is a lightweight format and parser being developed by Boost used to prepare technical documentation for software, mainly for for Boost C++ Libraries. Quickbook files (.qbk) are used as input for BoostDoc which in turn is an extension of DocBook.

Quickbook is a textual format, it feels quite similar to AsciiDoc or some sort of Wiki dialect but dedicated for documenting C++ programming. It is extremely easy to grasp while drinking a single short coffee.

Anyway, it seems it is going to be a quite a book after all elements of Boost.Geometry are documented. One of the challenge I’ve found is to collect all bits necessary to document C++ concepts defined by Boost.Geometry. Unfortunately, Doxygen is not an ideal tool for this purpose, so current version of the documentation lacks of some sections of concepts description. So, I have to dig the source code to find out formal definitions and details of valid expressions and semantics.

Another challenge related to concepts is to find best way to structure their documentation. I started to browse documentation of existing Boost libraries looking for examples and what I found is that there is no best example. Various libraries document concepts in very different way.

A concept is a set of requirements consisting of valid expressions, associated types, invariants, and complexity guarantees

David Abrahams, Generic Programming Techniques

For example, neatly Boost.Fusion documents concepts with Quickbook, though some elements seem to be omitted. Boost.Graph doesn’t document with Quickbook, looks good, but some details are missing to me, for instance, titles in headers of tables saying what is what is return type and pre-/post-condition for valid expressions, etc. Documentation of Boost.IOStreams concepts sound well. On the other hand, Boost.GIL is an example of why Doxygen should not be used to document concepts of a C++ library.

It looks to me the old good Standard Template Library Programmer’s Guide at SGI is still a best and most complete example of how C++ concepts should be documented.

Given these experiences, I started to think of a way to improve the way concepts are documented within Boost. I believe it would be a good idea to have predefined block for concept in Quickbook. Something along these lines:

[concepttype [Point Concept]
  [this is a concept for 0-dimensional geometry]
  [notation
    [term 1] [description 1]
  ]
  [refinement [concept 1] [concept 2]]
  [associated
    [type 1] [description 1]
  ]
  [expressions
    [name 1 [expr 1]
      [type requirement 1] [return type 1]
  ]
  [semantics
    [name 1 [expr 1]
      [precondition 1] [semantic 1] [postcondition 1]
  ]
  [complexity [...]]
  [invariants
    [invariant 1] [description 1]
  ]
  [models [model 1] [model 2]]
  [notes
    [ note 1] [ note 1]
  ]
  [seealso ...]
]

I posted my proposal to boost-docs list explaining the motivation in details. It’s an interesting experience of a C++ documentation craftsman, anyway. (BTW, Daniel James just announced Quickbook port to Spirit 2.)