Most vexing parse

The combined usage of boost::thread and functor could lead to the infamous "most vexing parse" issue. It a sort of misunderstanding from the coder and the compiler, caused by an ambiguity in C++ syntax.

You would find its full description in Item 6 of Effective STL by Scott Meyers. But, in few words, in this mixup the coder thinks he is calling a default constructor to create an object to be used as parameter for a function call, while the compiler gets that he wants to declare a function.

The solution requires the coder to be polite and to explain more clearly what he really wants.

In our case the issue could raise with a minimal change in the code. Say that we decided to give a default to the Count constructor:
Count(const int multi = 1) : multi_(multi) {}
Our idea was that in this way we'd save some typing, since 1 was the most popular choice for creating a Count.

This leads us to create a thread writing (wrongly):
boost::thread t1(Count());
From our point of view the code is clearly the request of creating a thread object named t1, passing to it a Count instance initialized with the default value (one).

Unfortunatly, for the compiler we declared nothing less than a function named t1, returning a boost::thread object and accepting in input as parameter an unnamed pointer to function with no parameter and returning a Count object.

Why should we ever want to declare such a thing? Well, there is no use in discussing with a compiler. Better to clarify what we mean, adding an extra pair of round brackets:
boost::thread t1((Count()));

No comments:

Post a Comment