How to add offset to shared_ptr?

I tried to create a single memory panel for my matrix class, because std::vector<std::vector<double>> did not give the performance that I wanted. So I decided to use a single 1d array. So I thought about using shared_ptr double for this.

Declare the variable I made:

std::shared_ptr<double> matrix;

To allocate memory for the declared shared pointer, I did:

matrix = std::make_shared<double []> (row*col);

Now, to access an element to assign something to a specific location in the matrix:

*(matrix + r*col + c) = 0.0;

It gives me an error saying

`error: no matches for 'operator +' (operand types: 'std :: shared_ptr' and 'size_t')

I thought we could use + for the pointer. Why does this not allow adding a scalar value to the index?

+5
source share
1 answer

std :: shared_ptr is not a pointer, it is a class that encapsulates a pointer. Therefore operator + does not work on shared_ptr

If you have a regular pointer ( double* matrix ), everything will be fine. You can get a regular pointer from shared_ptr using get ()

This changed your code to *(matrix.get() + r*col + c) = 0.0;

Equivalent expression matrix.get()[r*col + c] = 0.0;

Another way to store data (unless you want it to be shared) is to use std :: vector :

 std::vector<double> matrix(row * col); matrix[r * col + c] = 0.0; 

using a vector gives an advantage when creating a debug assembly, operator [] can check if the expression r * col + c returns an invalid index (for example, if r> = col)

+6
source

Source: https://habr.com/ru/post/1259294/


All Articles