简体   繁体   中英

C++ pointers memory usage

Keep going around circles, but I am still unclear about this. Have a feeling about the answer; but not sure. Which code below consumes more memory? [Should be the former, if I am correct.]

double x;
double* y = new double(x);

OR

double x;
double* y = &x;

In the former, two double s exist ( x , and the one pointed to by y ). x is allocated on the stack, and y on the heap.

In the latter, only one double exists ( x , also pointed to by y ). There are no heap allocations involved here.

So, on the face of it, you are correct.

In both cases , there exists one double on the stack, and one double* also on the stack. The difference between the two is that in the first case, there is also a double allocated on the heap (the one allocated by new double(x) ). Therefore the first case requires more storage.

The following consumes sizeof( double ) + sizeof( double* ) plus sizeof( double ) on the heap:

double x;
double* y = new double(x);

The following consumes sizeof( double ) + sizeof( double* ) :

double x;
double* y = &x;
double x;
double* y = &x;

will take sizeof(double) + sizeof(void*)

double x;
double* y = new double(x);

will take sizeof(double) + sizeof(double) + sizeof(void*) . Also allocates memory from the heap via new . There will also be more bookkeeping overhead based on the heap allocator (especially if it breaks up a contiguous free chunk), and it will be slower.

The first one. There are two doubles and one pointer (usually long int)

In the second one you have only one double and one pointer

In this example:

double x;
double* y = new double(x);

you have the memory space for x , for the pointer y , and the new allocated memory that stores a copy of x , and is pointed by y .

In this example:

double x;
double* y = &x;

you have the memory space for x , for the pointer y which points to x . This uses less space.

first allocate space for 1 double at first line, then at second line allocates space for 1 pointer and another double, and copies value from the old one. The latter allocate space for 1 double and for a pointer. So first is more memory consuming.

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