I'm trying to replace a function which searches a container of pointers and provides the found element as an outgoing reference by using unique_ptr
.
Below is a simple example to demonstrate the situation when using plain pointers:
bool find_ref_in_list(int n, const std::list<int*>&l, int*& element)
{
auto iter = find_if(l.begin(), l.end(), [n](int* x)
{
return (*x == n) ? true : false;
});
element = *iter;
return true;
}
Trying to encode this by using unique_ptr
leads me to the following code which causes an error when storing the result to the element reference.
bool find_ref_in_list(int n, const std::list<std::unique_ptr<int>>&l, std::unique_ptr<int>& element)
{
auto iter = std::find_if(l.begin(), l.end(), [n](const std::unique_ptr<int>& x)
{
return (*x == n) ? true : false;
});
element = *iter; // causes error because assignment operator=
return true;
}
In this situation I don't intend to share the ownership of the element, so shared_ptr
is not an option. Also I do not want to take the ownership so a move
operation isn't a good idea.
I'm aware that I could simply use an iterator
as outgoing reference or the raw pointer by get()
, but I think that would somehow obstruct the idea of unique_ptrs.
So the question if it is possible to provide the outgoing reference to a unique_ptr or which is the right technique to encode this problem for unique_ptrs. I'm looking especially for a solution which works without using 3rd party libraries like boost.