C++ implements dynamic allocation of const object instances

  • 2020-04-02 02:49:15
  • OfStack

This article illustrates the method of dynamically allocating const objects in C++. Share with you for your reference. Specific methods are analyzed as follows:

A, create,

In C++, const objects are allowed to be created dynamically in the following format:


const int *p = new const int(128);

Like other constants, dynamically created const objects must be initialized at creation time, and their values cannot be changed after initialization.

Second, delete,

Although you cannot change the value of the const object, you can delete dynamically created const objects in the following format:


delete p;

This, like a normal object, can be deleted.

Examples of application scenarios

1. Load the configuration file

The data read in from the configuration file can be used to initialize the const object for use by subsequent programs.

The pseudo-code is as follows:


int num;

... //Read the configuration file and populate the num with the configuration data

const int *pNum = new const int(num); //Initialize the const object with num

cout<<*pNum<<endl; //Use the const object

...

delete pNum;

2. Create an array

Consider const objects when the size of an array depends on some dynamic factor (such as a configuration file).

The pseudo-code is as follows:


int num;

... //Gets the value of num

const int *pNum = new const int(num); //Initialize the const object with num

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 scenes, which are temporarily recorded here for later reference.

Hope that the article described in the C++ programming to help you.


Related articles: