Next: name mangling Prev: bug reports Up: User Problems Top: Top

3.7. Porting programs from other compilers to g++

``I have a program that runs on <some other C++ compiler>, and I want to get it running under g++. Is there anything I should watch out for?''

First, see the questions on placement new syntax and static data members.

Secondly, if the porting problem relates to the resolution of overloaded operators or functions, you might try the -fansi-overloading switch in g++ 2.5.0 or later. This switch enables new code that attempts to match the ARM specification of overloaded argument resolution better.

There are two other reasons why a program that worked under one compiler might fail under another: your program may depend on the order of evaluation of side effects in an expression, or it may depend on the lifetime of a temporary (you may be assuming that a temporary object "lives" longer than the standard guarantees). As an example of the first:

Novice programmers think that the increments will be evaluated in strict left-to-right order. Neither C nor C++ guarantees this; the second increment might happen first, for example. func might get 3,4, or it might get 4,3.

The second problem often happens with classes like the libg++ String class. Let's say I have

and I say

because I know that class String has an "operator const char*". So what really happens is

where I'm pretending I have a convert() method that is the same as the cast. This is unsafe, because the temporary String object may be deleted after its last use (the call to the conversion function), leaving the pointer pointing to garbage, so by the time func2 is called, it gets an invalid argument.

Both the cfront and the g++ behaviors are legal according to the ARM, but the powers that be have decided that compiler writers were given too much freedom here. The ANSI C++ committee has now come to a resolution of the lifetime of temporaries problem: they specify that temporaries should be deleted at end-of-statement (and at a couple of other points). This means that g++ now deletes temporaries too early, and cfront deletes temporaries too late.

For now, the safe way to write such code is to give the temporary a name, which forces it to live until the end of the scope of the name. For example:

Finally, like all compilers (but especially C++ compilers, it seems), g++ has bugs, and you may have tweaked one. If so, please file a bug report (after checking the above issues).