Sign in to follow this  
noatom

How do I increment a shared pointer?

Recommended Posts

noatom    927

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
Madhed    4095

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
noatom    927

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
Madhed    4095

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
richardurich    1352

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
ChaosEngine    5185

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this