Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of both scalar and array in smart pointer

How can I use both scalar and array in smart pointer?

The old way of using new and delete pointer:

int *p;

if (useScalar) {
    p = new int;
} else {
    p = new int[10];
}

if (useScalar) {
    delete p;
} else {
    delete[] p;
}

In smart pointer, I have to use 2 pointers for each scalar and array pointer:

std::unique_ptr<int> p1(new int);
std::unique_ptr<int[]> p2(new int[10]);

How can I decrease to use only 1 smart pointer?

like image 849
MiP Avatar asked Apr 20 '16 10:04

MiP


People also ask

Why do we use array of pointers?

The Application of Arrays of Pointers Let us assume that we want to build an enclosed system, and this system uses a different kind of thermometer for measuring the temperature. Now, in this case, we can use an array for holding the address of memory for every sensor.

Can we use array in pointer?

C. In this program, we have a pointer ptr that points to the 0th element of the array. Similarly, we can also declare a pointer that can point to whole array instead of only one element of the array. This pointer is useful when talking about multidimensional arrays.

What is the relationship between pointer and array?

An array is represented by a variable that is associated with the address of its first storage location. A pointer is also the address of a storage location with a defined type, so D permits the use of the array [ ] index notation with both pointer variables and array variables.


1 Answers

If you use a custom deleter, you can use the same type for either pointer.

std::unique_ptr<int, void(*)(int*)> p = {nullptr, [](int*){}};
if (useScalar) {
    p = {
        new int,
        [](int* p){delete p;}
    };
} else {
    p = {
        new int[10],
        [](int* p){delete[] p;},
    };
}
like image 186
eerorika Avatar answered Oct 01 '22 19:10

eerorika