Saturday, January 26, 2013

RaiiCaps with GCC: error: cannot declare ‘::main’ to be a template

The idea of the raiicap class is described at RaiiCap pattern: Injected Singleton alternative for C++. However, the version of GCC I am using is affected by a bug ([Bug c++/24449] Unable to declare friend main() from class template) that prevents using the raiicap idea directly without code modifications.

Below is an attempt at a workaround:

When MAIN_IS_THE_FRIEND is defined above, we fail the compile on GCC (version 4.6.3) with:

/usr/bin/g++ -g -fPIC -Wall -Werror -Wsynth -Wno-comment -Wreturn-type test.cpp -c -o test.o
test.cpp:13:41: error: cannot declare ‘::main’ to be a template
make: *** [test.o] Error 1

But if we undefine MAIN_IS_THE_FRIEND then the compile succeeds.

This may or may not prevent malicious intent: In practice, these classes will likely be defined in header files, which can be included in other translation units, and exploited. For instance, it might still be possible for someone to define their own file static version of mainSurrogate in their own translation unit, and use it in that other translation unit to instantiate instances of Resource. However, this may just be enough to keep the majority of developers within the bounds of the original intent.

No comments:

Post a Comment