c++ - 指针 vector 的复制构造函数

标签 c++ pointers vector

我正在尝试创建一个包含指针 vector 的节点类。这是我的代码:

node.h:

#ifndef NODE_H
#define NODE_H

class node
{
public:
    vector<node*> next;
    void add_arc(node & a)

    string some_string;

#endif

节点.cpp:

void node::add_arc(node & a)
{
    node *b = &a;
    next.push_back(b);       //only copyies nodes
}

ma​​in.cpp:

int main()
{
    vector<node> nodes;
    node a;
    node b;
    node c;

    a.somestring = "a";
    b.somestring = "b";
    c.somestring = "c";



    a.add_arc(b);      //a should point to b
    a.add_arc(c);      //a should point to c

    nodes.push_back(a);
    nodes.push_back(b);
    nodes.push_back(c);

    cout << nodes[0].next.size() << endl;           // prints "2", works fine
    cout << nodes[0].next[0]->some_string << endl;  //empty
}

我认为这就像重载 push_back 一样简单:

void push_back(vertex * pointer)
{
    next.push_back(pointer);
}

但我认为我确实需要一个复制构造函数或其他一些方法来完成这项工作。我将如何为指针 vector 执行此操作?

编辑:我想我没有解释好。看看这个问题的答案: Segmentation fault when accessing a pointer's member function in a vector 使“a”成为引用对我不起作用

最佳答案

有效...

您的代码按预期生成正确的输出(请参阅 online demo):

2
b

...但是这种设计不是面向 future 的

但是这个结果在某种程度上与运气有关,因为在您的代码片段中:

  • nodes 中的节点vector 是原始对象的拷贝,包括它们的所有指针
  • 这些指针指向的局部对象a、b、c仍然存在

然而,在更复杂的代码中,您很快就会遇到悬空指针。 想象一下:

  • 错误示例 1:您创建了一个图,将所有节点直接保存在节点 vector 中。然后在节点之间添加第一条弧线。只要您将新节点添加到 vector 中,就可能会发生重新分配,并且您可能会看到所有 next。指针无效。
  • 错误示例 2:您像以前一样初始化了一个图形,但是在 main 调用的函数中.在这种情况下,一旦您从此函数返回,所有本地节点都会被销毁,并且 vector 的节点将指向不再存在的对象。 UB保证!

如何改进?

您的设计无法识别所有节点都属于同一个图。

有一个快速而肮脏的出路:始终从免费商店创建节点,并将它们存储在 vector<node*> 中。 .

vector<node*> nodes;
node *a = new node("a");  // Imagine a node constructor 
node *b = new node("b");
a->add_arc(b);            //change signature, to accept a pointer 
nodes.push_back(a);
nodes.push_back(b);

有一个更好的方法:进一步改进以前的方法,但使用shared_ptr<node*>确保不再引用的节点(既不是节点 vector ,也不是弧)被自动销毁。

还有一种更好的方法:将节点封装在表示图形的类中。在这种情况下,您可以考虑使用 vector<nodes>并替换 next 中的指针, 通过 vector 中目标节点的索引。没有指针,但图形的完美复制会容易得多。不再有内存管理的麻烦。

class node    // just to give the general idea
{
public:
    vector<int> next;  // not usable without the graph 
    void add_arc(int a)
    string id;
};

class graph {
    vector<node> nodes; 
public:  
    void add_node (node a);  
    void add_arc (string from, string to);  
    node& operator[] (size_t i); 
    ...
}; 

关于c++ - 指针 vector 的复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37093000/

相关文章:

c++ - SCTP recvmsg返回EFAULT(错误地址)

c++ - 如何使用指针合法访问对齐错误的对象?

c++ - 快速字符串搜索?

c++ - vector 乘法中的 SIMD 与 OMP

c - 将 sqlite3_column_text() 返回到文字字符串

C++ 检查元素是否为 std::vector

c++ - “Make”因Clang错误而失败-如何从Clang中获取错误?

c++ - 无法连接到 SMTP 服务器

c++ - 如何使用用户输入的变量来定义另一个变量

c - char *a[]= {"hello", "world"}; 之间有什么区别?和 char a[][10]= {"hello", "world"};?