How can one use TSharedPointer with multidimensional arrays?

When using shared pointers with multidimensional arrays, as in the following snippet:

//.h file

MyClass MultiArray[8][25];
TSharedPtr<MyClass> MultiArrayRef;

-----------------------------------------------------------------

//.cpp file

MultiArray[8][25] = {};

MultiArrayRef = MakeShareable(new MyClass[8][25]);

The compiler returns an error:

C:\Program Files\Unreal Engine\4.2\Engine\Source\Runtime\Core\Public\Templates\SharedPointer.h(473): error C2440: 'initializing' : cannot convert from 'MyClass (*)[25]' to 'MyClass *'

Is this an incorrect use of the SharedPointers constructor, or are SharedPointers not designed to work with multi-dimensional arrays?

Hi Chris,

TSharedPtr is not designed to work with arrays of any kind, as it deletes its referenced object via delete, not delete[]. There’s a chance that a one-dimensional array may work by chance if your class has a trivial destructor, but it’s generally undefined behaviour. Unfortunately, MakeShareable cannot divine the dimensionality of the original new call which you have passed it, so we cannot catch this kind of error.

If you want an array, use TArray. If you want a multi-dimensional array, you can have a TArray of TArrays (for jagged arrays) or just a regular TArray where you maintain the resizing and indexing yourself (for non-jagged arrays with contiguous rows).

Steve