Remedy for applying a new operator to an array pointer

In C, I do

int (*ptr)[100];
ptr=malloc(sizeof *ptr); // this is the easy/error proof way of doing it

Is there a way to check for errors in C ++ using the operator new

int (*ptr)[100];
ptr=new __what_comes_here?
+4
source share
4 answers
int (*ptr)[100];

means ptr- this is a pointer that should contain the address of an array of 100 integers. In other words, technically, if you have, something like:

int arr[100];  // automatic (compile time allocated) object of 100 integers

Then you can use:

ptr = &arr;

But this is not so. That way you can make a simple pointer. If you want to switch to dynamic, you either switch to the equivalent malloc:

int *p = new int[100];  // do `delete[] p` later to reclaim memory

, p - , .

, :

std::vector<int> v(100);

100 , :

int a[100];  // C-style

std::array<int, 100> arr;  // C++11 onwards

new , , unique_ptr :

std::unique_ptr<int[]> p(new int[100]);
+3

, , , , .

template<typename>
struct deref;

template<typename T>
struct deref<T*>
{
    typedef T type;
};

int main() {
    int (*ptr)[100];
    ptr = new deref<decltype(ptr)>::type[1];
    return 0;
}

, [1] , new int*. , "" .

, delete[], undefined.

, , , godbolt .

+1
typedef int IntArray[100];

int main()
{
    IntArray* p = new IntArray[1];

    delete[] p;
    return 0;
}

, delete[].

0

, , , , .

template <typename T, std::size_t N>
void populate_ptr(T (*&ptr)[N])
{
    // Its a shame the return value of new T[N] is T*, not T(*)[N]
    ptr = reinterpret_cast<T(*)[N]>(new T[N]);
}

int (*ptr)[100];
populate_ptr(ptr);
// Don't forget to delete[](ptr) later!

You cannot output patterns by return values, therefore you cannot use assignment, but passing by reference should be equivalent for all use cases.

Not that it's a great way to handle this, but the ability to infer template type versus C-style arrays is sometimes useful from time to time.

0
source

Source: https://habr.com/ru/post/1649743/


All Articles