4

I'm trying to troubleshoot a c++ problem where two parts of my code are returning different results for the sizeof() operator.

Here's what I run

MyClass* foo = new MyClass();
int size = sizeof(*foo)

I place this code in two different sections of my project and I get two different results. One time it 2254, another is 2284. I can look at the memory layout and one area shows the internal members as byte-aligned, another area it's word aligned.

I look at the dissasmbly and see that the sizeof() values are actually part of the machine code. Would this be a bug in the compiler or the linker? Why would two parts of the same project view the same class differently?

EDIT:

Let me provide a more clear example that I just ran to show that this is NOT a ODR violation.

I just made a brand new class as such

class TestAlignClass
{
public:  
    TestAlignClass() { }
    ~TestAlignClass() { }

private:
    char charArray[3];
    int myInt;
};

If the class is aligned to 4, it should return sizeof() = 8 which is what I want. But there are certain classes in my code that return sizeof() = 7.

In fact when I step into the new() operator, sometimes it allocates 7 bytes and sometimes it allocate 8.

I am linking several projects together and I thought it had to do with project settings at first, but different parts of the same project will show the discrepancy.

4

1 回答 1

8

sizeof在编译时进行评估。

至于为什么sizeof在两个不同的地方为同一个构造返回不同的值,类必须以某种方式在不同的翻译单元中以不同的方式定义。

我首先要看的一个地方是包装。如果一个 TU 中存在#pragma pack (1)类型表达式,而另一个 TU 中没有,则可能会导致差异。它也可能表明违反了单一定义规则,但这是另一回事。

另一个可能更奇特的事情是#ifdef类型宏的存在,它会影响类的一部分。

正如@MooingDuck 在评论中正确观察到的那样,该错误极有可能在您的代码中。不要假设编译器有缺陷。

于 2013-06-28T19:45:47.137 回答