Reputation: 97918
How can I create a pointer to a pointer that is wrapped inside a unique_ptr? In other words, is there a sound way to write this function:
int **getIterator(std::unique_ptr<int>& p)
{
/* error: lvalue required as unary ‘&’ operand */
return &p.get();
}
Upvotes: 0
Views: 823
Reputation: 12058
I want to return a pointer to use as an iterator with an interface that expects iterators. I want to pass algo(getIterator(X), getIterator(X)+1) so that single items look like collections.
You are using std::unique_ptr<int>
. If I understand your problem correctly, you are trying to do something, that is not necessary in this case: if you want to iterate through int
s, you need int*
(pointer to object), not int**
(pointer to pointer).
Use this:
int* getIterator(std::unique_ptr<int>& p)
{
return p.get();
}
Then, you can do what you wanted:
algo(getIterator(X), getIterator(X) + 1);
I expect algo
being defined similar to this:
template <class Iter>
Result_type algo(Iter begin, Iter end)
{
//algorithm
}
If you do something like:
std::unique_ptr<int> p = /* initialize */;
algo(getIterator(p), getIterator(p) + 1);
You will receive two parameters of type int*
, that can be safely moved forward/backward and dereferenced to get current object's value.
Upvotes: 2