2

Can we use [] operator or ++ with unique pointer or shared_pointer? As we use it for raw pointer

int * a = new int[10];
a[0] = 2; // We can use [] operator;
  • Is there a similar way for smart pointers?

  • If it is there should when should I use this?

  • If it is not there then Why?
  • Is it also possible for MultiDimensional Array ?
2
  • cplusplus.com/reference/memory/unique_ptr Do the same for shared_ptr Commented Oct 21, 2016 at 6:49
  • You can use a shared_pointer on an array : std::shared_ptr<std::array<int, 10>> Commented Oct 21, 2016 at 6:49

2 Answers 2

5

Both std::unique_ptr and std::shared_ptr provide operator[] for indexed access to the stored array. You can use them if what they're managing is array.

operator[] provides access to elements of an array managed by a unique_ptr.

e.g.

std::unique_ptr<int[]> a(new int[10]);
a[0] = 2; // We can use [] operator;

Note the index shall be less than the number of elements in the array; otherwise, the behavior is undefined.

Unfortunately we can't use operator++ on them directly; that's not what smart pointers being supposed to do, they're usually used for managing pointers.

And I'll suggest you use std::vector or std::array if you just want an array.

Sign up to request clarification or add additional context in comments.

4 Comments

It is pointer to int[] not to int as we have in case of raw pointer. Also Can we use ++ opertator with it.
@Anshuman What pointer did you mean? They provide same hehavior as raw pointers. Yes we can't use operator++ on them directly; that's not what smart pointers being supposed to do.
Thanks, What about MultiDimensional Array
@Anshuman Basically they're same, 2-d array could still be regarded as 1-d array of something (i.e. an array). But use it with smart pointers seems confusing, you could use std::vector or std::array like std::vector<std::vector<T>>.
1

Yes.

Here is an example http://en.cppreference.com/w/cpp/memory/unique_ptr/operator_at

 std::unique_ptr<int[]> fact(new int[size]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.