So I am trying to figure out how I could use smart pointers to produce the correct array 0...24. First thing that puzzles me is that, by looking at the third array of the output, it seems that all places of the smp_pi point to the same int array of size 5, instead of 5 different arrays of size 5. I was expecting to point to different arrays since a new smart pointer is declared in every loop (line 34). Second I was wondering about the syntax in line 42 that does not compile. So, if someone could enlighten me on how this could work correctly (for arbitrary size of arrays offcourse) but also what exactly I conceive erroneously here, it would be very helpful.Thank you!
There are several reasons why line 42 won't compile.
The most obvious one is that smp_pi[j] is a int* whereas smp_i is a unique_ptr<int>.
If you want to store smart pointers in your array, then your array has to be a smart pointers' array, not an int* array.
An other reason is that you're using unique_ptr. It's named unique_ptr for a reason. Read the doc !!
As for the 3rd array, it's because you declare your unique_ptr inside the 2nd loop.
A unique_ptr is supposed to free the memory of the managed pointer when its destructor is called. Since your smart pointer is declared inside a loop, each time the loop is exited the allocated memory is freed. So all the pointers you store with smp_pi[j]=&smp_i; point to freed memory.
The reason all the line have the same value is just chance. Since you deallocate your array after each inner loop, there's a probability that at the next iteration's allocation your system allocator may choose the memory that was just freed. In that case the pointer returned by new will be the same as the one of the previous row.
It can be verified by checking if all smp_pi[j] contain the same address.