My task is to generate a square matrix of zeros in a function and return it. There are plenty ways to do this, but I decided not to go with returning the matrix by value for efficiency. I went for a pointer approach like in this answer, but since it requires manual cleaning memory (and also as far as I know it's better to use smart pointers), I decided to turn it into std::unique_ptr
, but I can't get it to work. This is my code:
#include <iostream>
#include <memory>
std::unique_ptr<std::unique_ptr<int>[] > GenerateMatrix(const int &n) {
std::unique_ptr<std::unique_ptr<int>[] > matrix(new std::unique_ptr<int>[n]);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i].get()[j] = 0;
}
}
return matrix;
}
int main() {
int n = 4;
auto matrix = GenerateMatrix(n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
std::cout<<matrix[j].get()[i]<<" ";
}
std::cout<<std::endl;
}
return 0;
}
What do I do wrong here? Is this approach even correct?