# How do I increment a shared pointer?

This topic is 2082 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

shared_ptr<PxVec3> vertices = shared_ptr<PxVec3>(new PxVec3[data->points->size()],
[](PxVec3* p){delete[] p; });

turns out I can't use vertices[5],neither can I use vertices++

How am I supposed to access any other element in the array?

##### Share on other sites

That's not possible.

What are you trying to accomplish?

Why don't you use a std::vector instead of a plain array? i.e a shared_ptr to a std::vector

##### Share on other sites

I'm trying to get the same behaviour as int *i = new int[30]; so I can do i[5] = 10.

I revised the code,but it still doesn't work:

shared_ptr<PxVec3> vertices(new PxVec3[data->points->size()],
[](PxVec3* p){delete[] p; });

##### Share on other sites

Well, there's shared_ptr::get which returns the underlying raw pointer.

So I guess you could do (didn't test this): i.get()[5] = 10;

But I suggest you don't use shared_ptr-to-array.

##### Share on other sites

I have no idea if unique_ptr does what you need, so I'll just answer your actual question. If you need shared_ptr, you use get()[5] syntax. You can also override operator [] so you can use i[5] syntax. Quick example:

class shared_ptr_int_array : public shared_ptr<int>{
public:
shared_ptr_int_array(int* p) : shared_ptr<int>(p) {}
int& operator[](ptrdiff_t i){ return *(get() + i); }
};

int main(){
shared_ptr_int_array i(new int[50]);
i[5] = 10;
return 0;
}

I didn't specify the destructor, so make sure you use delete[] instead of delete. You already knew that in your original post, but I guess it's obligatory to mention it.

##### Share on other sites

Let's take a step back.

Ask yourself what you are trying to achieve with this. What are the ownership semantics of vertices? What is the scope of the variable and it's expected lifetime?

Once you have answered those questions, you can then make an educated decision on which container to use.

But based solely on your code snippet, I'd agree with madhed and say you most likely want a vector.

• ### Game Developer Survey

We are looking for qualified game developers to participate in a 10-minute online survey. Qualified participants will be offered a \$15 incentive for your time and insights. Click here to start!

• 16
• 11
• 23
• 42
• 75