c++classmemory

will compiler reserve memory for this object?


I have following two classes:

template <size_t size>
class Cont{
 public:
 char charArray[size];
};
template <size_t size>
class ArrayToUse{
 public:
 Cont<size> container;
 inline ArrayToUse(const Cont<size+1> & input):container(reinterpret_cast<const Cont<size> &>(input)){}
};

I have three following lines of code at global scope:

const Cont<12> container={"hello world"};
ArrayToUse<11> temp(container);
char (&charArray)[11]=temp.container.charArray;

In totality of my code The only usage of "container" object is for initialization of an object of "ArrayToUse" class as mentioned and after initialization of "charArray" reference to "temp.container.charArray" I'll use that reference in rest of my code, now I'm wondering does compiler reserve memory for "container" object since that's got a temporary usage?


Solution

  • Any variable defined at global scope has memory reserved for it at compile time. That does not mean it's guaranteed to be properly initialized, but it's there all the same.

    At link-time, Visual C++ offers the option to strip unused data and functions via /OPT - see here.