Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does this C++ class containing a variable size array use dynamic memory allocation?

Does doing something like this use dynamic memory allocation?

template <class T, int _size> 
class CArray 
{ 
public:
    ... 
private:
    T m_data[_size]; 
};

Can someone explain to me what's going on behind the scenes when I create the object?

CArray<SomeObject, 32> myStupidArray;
like image 936
SpooneyDinosaur Avatar asked Dec 01 '22 12:12

SpooneyDinosaur


2 Answers

No, it will be allocated in-place (e.g. either on the stack, or as part of a containing object).

With templates the parameters are evaluated at compile-time so your code effectively becomes;

class CArray 
{ 
public:
    ... 
private:
    SomeObject m_data[32]; 
};
like image 103
Andrew Grant Avatar answered Dec 04 '22 14:12

Andrew Grant


As mentioned in the other answers, templates are evaluated at compile time. If you're interested you can have g++ spit out the class hierarchy where you can verify its size:

template <class T, int _size>
class CArray
{
public:
private:
  T m_data[_size];
};

int main(int argc, char **argv) {
  CArray<int, 32> myStupidArray1;
  CArray<int, 8> myStupidArray2;
  CArray<int, 64> myStupidArray3;
  CArray<int, 1000> myStupidArray4;
}

Compile with -fdump-class-hierarchy:

g++ -fdump-class-hierarchy blah.cc

There should be a file named blah.cc.t01.class in the current directory:

Class CArray<int, 32>
   size=128 align=4
   base size=128 base align=4
CArray<int, 32> (0x40be0d80) 0

Class CArray<int, 8>
   size=32 align=4
   base size=32 base align=4
CArray<int, 8> (0x40be0e80) 0

Class CArray<int, 64>
   size=256 align=4
   base size=256 base align=4
CArray<int, 64> (0x40be0f80) 0

Class CArray<int, 1000>
   size=4000 align=4
   base size=4000 base align=4
CArray<int, 1000> (0x40be6000) 0
like image 45
codelogic Avatar answered Dec 04 '22 13:12

codelogic