A
A
andrewjabber2014-10-30 10:51:45
C++ / C#
andrewjabber, 2014-10-30 10:51:45

Is it possible to declare a two dimensional array on unique_ptr?

The following snippet declares a one-dimensional array managed by unique_ptr.

class A
{
public:
    static int i;
    A(){ j = i; cout << "A " << j << endl; i++; }
    ~A() { cout << "~A " << j << endl; }
    int j;
};
int A::i = 0;

int main()
{
    {
        unique_ptr<A[]> p1(new A[6]);
    }
    return 0;
}

Is it possible to declare a two-dimensional array on unique_ptr in the same way as it is implemented in vector?
#include <QDebug>
#include <iostream>
#include <memory>
using namespace std;
int main()
{
    int M = 2, N = 3;
    {
        #define VA std::vector<A>
        auto v2a = std::vector< VA >(M, VA(N));
    }
    return 0;
}

UPD
In the case of a complex two-dimensional array, it is better to base the solution on valarray , constructing it according to the following principle .

Answer the question

In order to leave comments, you need to log in

3 answer(s)
L
Lolshto, 2014-10-30
@andrewjabber

No. The fact is that new does not know how to create two-dimensional arrays.

int x  = 6; int y = 8;
ew int [x][y]; //error: the value of 'y' is not usable in a constant expression

But (similar to a vector, you can create an array of uniq_ptrs referring to an array of uniq_ptrs
typedef unique_ptr<A[]> a_arr;
typedef unique_ptr<a_arr[]> a_2d_arr;
a_2d_arr p1(new a_arr[8]);
p1[0].reset(new A[6]);
//...

But in general, this approach is not very convenient and very inefficient from the point of view of memory locality, and it is common to create a one-dimensional array of size m x n, which is then interpreted as two-dimensional.

A
AxisPod, 2014-10-30
@AxisPod

Well, there are no two-dimensional arrays in C++, there are only jagged arrays.
Therefore, you create a regular array with handles, shove it into unique_ptr and specify your delimiter.

X
xseven, 2014-10-30
@xseven

Everything is possible and the possibilities of the programmer are limited only by imagination.
Don't take it as a personal attack.
When such tasks arise, it is worth considering whether everything is in order with the architecture and is it possible to write it easier?
It seems to me that this will be hard to maintain and, apparently, you are using Qt and it is not very clear where storing a two-dimensional array of pointers can be useful there?
Perhaps it is worth considering the problem from a different angle and making it easier?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question