I have a class Node
that must have a list of its input Edge
's. These input Edge
's, however, are not meant to be modified by Node
, only accessed. I have been advised to use smart pointers for that matter, like this:
class Node
{
private:
std::vector<std::unique_ptr<Edge>> inEdges;
//...
public:
void inline AddEdge(std::unique_ptr<Edge>& edge) // could be const here too
{
this->inEdges.push_back(edge);
}
//...
}
So in the runtime I can create a list of nodes and edges and assign edges to each node:
int main()
{
std::vector<std::unique_ptr<Nodes>> nodes;
std::vector<std::unique_ptr<Edges>> edges;
nodes.push_back(std::make_unique<Node>(0, 0.5, 0.0));
nodes.push_back(std::make_unique<Node>(1, 0.5, 0.0));
edges.push_back(std::make_unique<Edge>(*nodes[0], *nodes[1], 1.0));
nodes[1]->AddEdge(edges[0]);
}
The compiler gives the error
Error 1 error C2280: 'std::unique_ptr>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)' : attempting to reference a deleted function c:\program files (x86)\microsoft visual studio 12.0\vc\include\xmemory0 593 1 sirs
It used to work with raw pointers inside the Node
's std::vector<Edge*>
, given that the signature of AddEdge
would be void AddEdge(Edge& edge);
, pushing back &edge
inside the vector.
What is wrong with my code? How should I proceed to correct it? Given that std::vector
cannot store references, because these are not assignable.
PS: I do not want to transfer ownership of the pointers to the Node
objects...
std::unique_ptr
can be moved, but not copied. YourAddEdge
should take it by value, and pass it further withstd::move
– milleniumbugNode
own the edges? If no, use raw pointers (orstd::reference_wrapper
). If yes: What's wrong with plainstd::vector<Edge>
instead? – Baum mit Augen♦Edge
's have their own dynamics... EachNode
is able to get only the output signal of eachEdge
... So aNode
does not own theEdge
's – Girardistd::shared_ptr
?" No. Smart pointers imply ownership. To just observe without owning use raw pointers and references. Use the latter (possibly viastd::reference_wrapper
if the pointers must never be 0. – Baum mit Augen♦