我有一个类Node
必须有一个输入列表 Edge
的。这些输入 Edge
的,但是,并不意味着被 Node
修改, 只能访问。有人建议我为此使用智能指针,如下所示:
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);
}
//...
}
因此在运行时我可以创建节点和边的列表并将边分配给每个节点:
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]);
}
编译器报错
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
它曾经在 Node
中使用原始指针的 std::vector<Edge*>
,鉴于 AddEdge
的签名将是 void AddEdge(Edge& edge);
, 推回 &edge
在 vector 中。
我的代码有什么问题?我应该如何进行更正?鉴于 std::vector
无法存储引用,因为它们不可分配。
PS:我不想将指针的所有权转移到 Node
对象...
最佳答案
您应该只移动 std::unique_ptr
的实例,以便将它们放在std::vector
中。否则你需要 std::shared_ptr
。
class Node
{
private:
std::vector<std::unique_ptr<Edge>> inEdges;
//...
public:
void AddEdge(std::unique_ptr<Edge>&& edge)
{
inEdges.push_back(std::move(edge));
}
//...
}
我已将 AddEdge
更改为采用右值引用,以便正确支持移动语义。
调用:
node.AddEdge(std::move(edge));
或者:
node.AddEdge(std::make_unique<Edge>(/*args*/));
顺便说一句。如果您发现您正在通过引用传递 std::unique_ptr
,这可能表明您应该使用 std::shared_ptr
。
此外,inline
在类内部声明的方法上是多余的。
关于c++ - 如何在 C++ 类中存储智能指针列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38905002/