0

I have one simple question here,

template <class T, MAX_ITEMS> Class A{ public: T buf[MAX_ITEMS]; } A<class_name, 1000> obj_A; 

When I declare obj_A using the last line, does it reserve a space? for sizeof(class_name)*1000 or it would reserve only if I use the new keyword for declaring obj_A?

4
  • 1
    "does it reserve a space? for sizeof(class_name)*1000" Yes. Depending on type, that may cause stack overflow, but at least it tries. Commented Feb 21, 2021 at 9:07
  • @AyxanHaqverdili "... that may cause stack overflow ..." No, at least not in the OP's example. Stack memory is only in play for function local variables. Commented Feb 21, 2021 at 9:12
  • 2
    I don't agree with the downvoting, the question is legit, I agree the same information could be found in various tutorial and a bit of googling, however, C++ can be daunting with new comers and if somebody is not familiar with templates can be easily be confused Commented Feb 21, 2021 at 9:13
  • @πάνταῥεῖ You are right. I presumed OP wants to do that in function scope as well. Commented Feb 21, 2021 at 9:14

1 Answer 1

1

does it reserve a space? for sizeof(class_name)*1000 or it would reserve only if I use the new keyword for declaring obj_A?

Yes, it will allocate enough memory for 1000 elements of that type statically. If your object has static/thread storage duration, then it is likely to work. If your object has automatic storage duration, depending on the type and stack size, it may cause stack overflow.

or it would reserve only if I use the new keyword for declaring obj_A?

If you use the new keyword, it will allocate the memory dynamically (dynamic storage duration). It generally doesn't matter how you create the object; if you manage to create an object of A<class_name, 1000> type successfully, it will surely have room for 1000 objects of type class_name in it.

Learn more about storage durations here.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.