Reputation: 266
I'm trying to replace a raw pointer implementation to smart pointer, so in this function call
int id = std::stoi(idToken->second);
auto newNode = std::find_if(_nodes.begin(), _nodes.end(), [&id](GraphNode *node) { return node->GetID() == id; });
I'm trying to change the raw pointer (GraphNode) to GraphNode unique ptr, to set the exclusive ownership of graphnode to the class it is declared, so in it's declaration I changed to
typedef std::unique_ptr<GraphNode> GraphNodeUniquePtr;
std::vector<GraphNodeUniquePtr> _nodes;
and in the function call I put
int id = std::stoi(idToken->second);
auto newNode = std::find_if(_nodes.begin(), _nodes.end(), [&id](GraphNodeUniquePtr node){ return node.get()->GetID() == id; });
on compiling, The compiler throws an error
error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = GraphNode; _Dp = std::default_delete<GraphNode>]’
Then I thought it could be the case to make a unique pointer with id and pass it to the lambda using the move function like
int id = std::stoi(idToken->second);
std::unique_ptr<int> idPtr;
*idPtr = id;
auto newNode = std::find_if(_nodes.begin(), _nodes.end(), [idPtr = std::move(idPtr)](GraphNodeUniquePtr node){ return node.get()->GetID() == *idPtr.get(); });
and now the compiler throws me another error:
error: use of deleted function ‘ChatLogic::LoadAnswerGraphFromFile(std::string)::<lambda(ChatLogic::GraphNodeUniquePtr)>::<lambda>(const ChatLogic::LoadAnswerGraphFromFile(std::string)::<lambda(ChatLogic::GraphNodeUniquePtr)>&)’
So I tried other approaches which I saw why it was not working and these two I could not understand why it isnt. I thought to make a shared pointer on GraphNode but with this I lost the exclusive ownership
How can I adapt this raw pointer implementation to unique pointer?
Thanks
Upvotes: 0
Views: 55
Reputation: 217810
You cannot pass std::unique_ptr
by copy. You might use reference instead:
[&id](const GraphNodeUniquePtr& node){ return node->GetID() == id; });
or, with const auto&
which would work for both versions
[&id](const auto& node){ return node->GetID() == id; });
Upvotes: 2