Answer the question
In order to leave comments, you need to log in
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;
}
#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;
}
Answer the question
In order to leave comments, you need to log in
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
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]);
//...
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.
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 questionAsk a Question
731 491 924 answers to any question