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?
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.
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.
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.
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;},
};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With