简体   繁体   中英

Memory allocation to class members in c++

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM