1

I'm working on a project and am not able to use bracket notation but must use smart pointers for arrays. However, as I've come to find, pointer arithmetic is not allowed with smart pointers. Is there a workaround for this?

Edit: The project is for a course and in the project specifications it says bracket notation cannot be used and dynamically allocated arrays in the form of smart pointers must be used.

1 Answers1

2

A specialization of unique_ptr was invented specifically for the purpose of doing pointer arithmetic. Use an 'array with unknown size' as your allocated type.

Example:

std::unique_ptr<int[]> p(new int[5]);
p[1] = 8;
std::cout << p[1];

To overcome the artificial and pointless limitation "bracket notation cannot be used", change p[1] to *(p.get()+1). But first make sure you understood the limitation correctly — in my opinion, no one in their right mind could demand such an uglification.

anatolyg
  • 26,506
  • 9
  • 60
  • 134