Class array length in C ++

Source: Internet
Author: User

See the following code:

Class operatornewcls {PRIVATE: // Enum {SZ = 10}; int arr [SZ]; public:/* after the Destructor is defined, the value of sizeof (operatornewcls) has not changed, ** but the value of new operatornewcls [size] is equal to (sizeof (operatornewcls) * size + 4 ), ** because the length size of the array is unknown in new operatornewcls [size] [-1. * ** If no destructor is defined, ** the value of new operatornewcls [size] is equal to sizeof (operatornewcls) * size */~ Operatornewcls () {}// this function must be public and static, although it does not display the specified staticvoid * operator new [] (size_t size) {cout <"operator [], size =" <size <Endl; return malloc (size) ;}; void test43 () {int size = 25; cout <"sizeof (operatornewcls) =" <sizeof (operatornewcls) <Endl; int * arr = (int *) New operatornewcls [size]; for (INT I =-1; I <size; ++ I) {cout <"arr [" <I <"] =" <arr [I] <"\ t" <Endl ;}}

The execution result is as follows:

Comment out operatornewcls destructor ~ After operatornewcls (), the execution result is as follows:

The difference is the length of the ARR array operatornewcls: After the Destructor is defined, the length is 1004 bytes, And the ARR [-1] is the number of array elements 25. After the Destructor is commented, the length is 1000 bytes, and ARR [-1] is a random number.

Why does the array length need to be stored after the Destructor is defined?

It may be because, after the Destructor is defined, the user needs to control the release of the heap memory. Therefore, each object in the logarithm group needs to call the Destructor one by one ", therefore, you need to store the number of array elements.

If you do not define the destructor, it means that the user does not control the release of the "heap memory", so there is no need to call the Destructor one by one, so there is no need to store the number of array elements.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.