tango-2
tango-2

Reputation: 94

How can i handle shared_ptr ++

 int main ()
 {
    shared_ptr<int[]> a(new int[2]);

    a.get()[0] = 5;
    a.get()[1] = 10;

    int* foo = a.get();

    ++foo;

    cout << *foo << endl;

    return 0;
}

The output is "10" as i expected. But I used regular pointer (int* foo) how can i implement/use ++ operator with only shared_ptr.

Upvotes: 0

Views: 510

Answers (3)

Tiger4Hire
Tiger4Hire

Reputation: 1091

What you are trying to do is semantically meaningless. A shared_ptr expresses the intent to own something (in this case an array of two int's). All it does is track ownership. If you increment a shared_ptr, does that mean you release the ownership of the first int? Or does it mean you own the second int twice? Either way is not what you are trying to do.
In general, use unique_ptr/shared_ptr only for ownership issues. To manipulate and use the memory directly, use a view class, something like a span. Not all compilers have this facility yet, so may have to use either the GSL library or write your own. However you implement it, it is better to make a separate object that views the object, but does not claim to own it. If you can tie the length of the array to pointer, this is better still.

Upvotes: 0

Zig Razor
Zig Razor

Reputation: 3495

There isn't another way.

The only method is to call get and the increment it in the copy returned from the get.

I attach you some usefull link :

smartpointer - shared_ptr

cppreference.com - shared_ptr

Upvotes: 0

Deduplicator
Deduplicator

Reputation: 45654

A std::shared_ptr contains two parts:

  1. A pointer to the bookkeeping.
  2. A payload-pointer which should be valid at least as long.

So, for your pointer-arithmetic, just use a dependent shared_ptr setting both individually:

shared_ptr<int[]> foo(a, a.get() + 1);

As an aside, an array-shared_ptr supports indexing, so no need to go over .get() for that.

Also, as long as you keep one shared_ptr aroud to keep the data live, there is nothing wrong (actually, it is expected and more efficient) with using raw pointers and references for processing.

Upvotes: 1

Related Questions