Dynamic Allocation of const objects (C ++)

Source: Internet
Author: User
Create

InC ++Allows dynamic creationConstObject in the following format:

Const int * P = new const int (128 );

Like other constantsConstThe object must be initialized at creation and its value cannot be changed after initialization.

Delete

Although it cannot be changedConstObject value, but can delete dynamically createdConstObject in the following format:

Delete P;

Like a common object, you can delete it.

ApplicationScenarioExample 1Load the configuration file

The data read from the configuration file can be used for initialization.ConstObject for laterProgram.

PseudoCodeAs follows:

Int num;

...//Read the configuration file and fill in the configuration dataNum

Const int * pnum = new const int (Num );//UseNumInitializationConstObject

Cout <* pnum <Endl ;//UseConstObject

...

Delete pnum;

2, Create an array

When the array size depends on some dynamic factors (such as configuration files), you can consider usingConstObject.

The pseudocode is as follows:

Int num;

...//ObtainNumValue

Const int * pnum = new const int (Num );//UseNumInitializationConstObject

Unsigned char _ DATA [* pnum]; //Create an array

...

Delete pnum

The sample code is as follows:

# Include <iostream> Using   Namespace  STD; Int  Main (){  Int  Num; CIN > Num;  Const   Int * Pnum = New   Const   Int  (Num );  Int Arr [* Pnum];  For ( Int I =0 ; I <* pnum; ++ I) Arr [I] = I;  For ( Int I = 0 ; I <* pnum; ++ I) cout <arr [I] < "   "  ; Cout < Endl;  Return   0  ;} 

Of course, there are many other scenarios. I have thought of these for the moment. I will record them here for future reference.

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.