inline functions returning incorrect results

874 views Asked by At

I have a large application that I am working on in C++, and we have a class where the inline functions are returning the wrong value. It looks like they are offset by one entry.

Here is an example of how the code is set up:

class Test
{

private:
    uint myVal1;    
    uint myVal2;
    uint myVal3;
    uint myVal4;

public:
    uint myFunct1() const { return myVal1 };
    uint myFunct2() const { return myVal2 };
};

What we are seeing is that myFunct1 returns myVal2 and myFunct2 returns myVal3. If I dont make the functions inlined everything works as expected.

Any ideas on why this would be happening?

Thanks in advance.

2

There are 2 answers

4
AnT stands with Russia On BEST ANSWER

(I assume that what you posted above is actually a fragment from some header file.)

Things like that typically happen when different source files in your program are compiled with different memory-layout-related settings, like class packing and alignment settings. Your header file is included into these different translation units and is interpreted differently because of the discrepancies in memory-layout settings.

Once you start passing your Test objects between these translation units, the problem reveals itself. One translation unit creates a Test object with one memory layout, then another translation units reads it or writes into it assuming a totally different memory layout. In your case it is your inline functions that get interpreted differently in each translation unit.

If you define your member functions as non-inline ones, they will assume the class memory layout specific to the source file in which they are defined. This will sweep the problem under the carpet and make things "work" (since the access functions are now tied to one memory layout), but nevertheless it is still not a good situation to have. It still can lead to various problems of similar nature down the road.

Make sure all source files in your program are compiled with exactly the same class memory layout settings.

P.S. As Fred noted in the comments, the discrepancy in the class memory layout between translation units can be caused by something as prosaic as forgetting to recompile a source file after modifying a header file the source file depends upon.

Another "popular" source of such problems is class definitions that depend on preprocessor directives (i.e. class layout "customized" by #ifdef/#endif segments). If you forget to #define something important in some source file that includes your header file, you might end up with different memory layout for the class in that source file.

2
Bo Persson On

No, inlined functions are (of course) required to have the same results as non-inlined functions. So, the problem must be somewhere else, in the code you are not showing. Perhaps the one magically setting the values of the private members?