Same class, different size ...?

Look at the code, then you will understand what bothers me.

test.h

class Test {
public:
#ifndef HIDE_VARIABLE
    int m_Test[10];
#endif
};

Aho.h

class Test;

int GetSizeA();
Test* GetNewTestA();

Aho.cpp

//#define HIDE_VARIABLE
#include "Test.h"
#include "Aho.h"

int GetSizeA() { return sizeof(Test); }
Test* GetNewTestA() { return new Test(); }

Bho.h

class Test;

int GetSizeB();
Test* GetNewTestB();

Bho.cpp

#define HIDE_VARIABLE   // important!
#include "Test.h"
#include "Bho.h"

int GetSizeB() { return sizeof(Test); }
Test* GetNewTestB() { return new Test(); }

Testprj.cpp

#include "Aho.h"
#include "Bho.h"
#include "Test.h"

int _tmain(int argc, _TCHAR* argv[]) {
    int a = GetSizeA();
    int b = GetSizeB();

    Test* pA = GetNewTestA();
    Test* pB = GetNewTestB();

    pA->m_Test[0] = 1;
    pB->m_Test[0] = 1;

    // output : 40     1
    std::cout << a << '\t' << b << std::endl;

    char temp;
    std::cin >> temp;

    return 0;
}

Aho.cpp does not #define HIDE_VARIABLE, therefore GetSizeA()returns 40, but Bho.cpp does #define HIDE_VARIABLE, therefore GetSizeB()returns 1. But, they Test* pAalso Test* pBhave the m_Test [] member variable.

If the class size Testof Bho.cppis 1, then pB is weird, isn't it?

I do not understand what is going on, please let me know. Thanks in advance.

Environment: Microsoft Visual Studio 2005 SP1 (or SP2?)

+3
source share
4 answers

(ODR). - undefined. , .

ODR, .

+13

undefined. ( Test - ). , , "" .

+13

ODR.

cpp, .

, Test * pA Test * pB - m_Test [].

, pB m_Test[], TestPrj , . , .
pB->m_Test[9] = 1; , pB, .

+2

, , (ODR).

, C/++. ( cpp) , - . , . , ( ) .

, , , .

, , , ODR - include , , .

, LPCTSTR, char wchar_t, , .. " ", , .

. (inlined), (- , ).

. . .

+1

Source: https://habr.com/ru/post/1773047/


All Articles