Sign in to follow this  

How do I increment a shared pointer?

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
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

Edited by Madhed

Share this post


Link to post
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 this post


Link to post
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.

Edited by Madhed

Share this post


Link to post
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 this post


Link to post
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.

Share this post


Link to post
Share on other sites
Sign in to follow this