Explicitly call the constructor

Source: Internet
Author: User
Class constructor is automatically called when an object instance is generated. Generally, constructor cannot be called directly.

However, in some special usage, developers need to call constructors to generate object instances.

For example, in memory pool programming, you need to apply for a large common memory in advance and convert a small block into an object instance during use,

In this scenario, you need to explicitly call the constructor.

Define Class AA:
Class AA {public: AA () {printf ("Hello AA: AA ();/N"); temp = 10 ;}; virtual ~ AA () {}; int Geti () {return temp ;}; PRIVATE: int temp ;};

We apply for a piece of memory in advance:

Char * PTR = (char *) malloc (sizeof (AA ));

When necessary, we need to convert the PTR to an AA object instance. If you use the following method to call it:

AA * AA = (AA *) PTR;

The constructor of Class AA will not be aroused, so this memory is not an AA object instance.

In this case, perform the following operations: AA-> Geti ();

No error is reported in the vc6.0 environment, but the returned data is incorrect.

Then we cannot use the memory as an AA instance. In this case, we need to use an explicit constructor call:

AA * AA = new (PTR) AA ();

Then, the constructor of AA is invoked to construct the instance.

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.