solti solti - 1 year ago 96
C++ Question

How to add offset to shared_ptr?

I was trying to create a single slab of memory for my matrix class because

was not giving the performance I wanted. So I decided to use single 1d array. So I thought of using shared_ptr of double for this.

To declare the variable I did:

std::shared_ptr<double> matrix;

To allocate memory for declared shared pointer I did:

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

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

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

This gives me error saying

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

I thought we could use
on pointer. Why is it not letting me add scalar value to the pointer?

Answer Source

std::shared_ptr is not a pointer, it's a class that encapsulates a pointer. That's why the operator + does not work on shared_ptr

If you had a regular pointer (double* matrix) then everything would be fine. You can get the regular pointer out of shared_ptr by using get()

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

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

Another way to store the data (if you don't want it shared) it is to use a std::vector:

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

using a vector presents an advantage when you have a debug build, the operator [] can check if the expression r * col + c returns an index that's invalid (for example if r >= col)