在向量中访问指针的成员函数时的分段故障 [英] Segmentation fault when accessing a pointer's member function in a vector
问题描述
由于某种原因,我得到一个分段错误;我使用一个指针的向量,它指向一个类对象。基本上我需要一个具有指向其他节点的指针向量的节点,在其他节点上做一个多图。以下是我的代码的相关部分:
For some reason I'm getting a segmentation fault; I'm using a vector of pointers, which point to a class object. Basically I need a node that has a vector of pointers to other nodes, in other to make a multigraph. Here's the relevant part of my code:
node.h:
#ifndef NODE_H
#define NODE_H
class node
{
public:
string content()
vector<node*> next; //causing the error
void add_arc(node a);
string rna_frag;
#endif
node.cpp:
void node::add_arc(node a)
{
node *b = &a; //b->content() works fine here
next.push_back(b);
}
string node::content()
{
return rna_frag;
}
main.cpp: b
$ b
main.cpp:
int main()
{
vector<node> nodes;
node a;
node b;
node c;
a.add_arc(b);
a.add_arc(c);
a.rna_string = "G";
nodes.push_back(a);
nodes.push_back(b);
nodes.push_back(c);
cout << nodes[0].content() << endl; //prints "G", works fine
cout << nodes[0].next.size() << endl; // prints "2", works fine
cout << nodes[0].next[0]->content() << endl; //segmentation fault
//cout << nodes[0].next->content() << endl; //also segmentation fault
//cout << nodes[0].next[0]->rna_frag << endl; //also segmentation fault
}
在这种情况下,nodes [0]是G,并指向其他2个节点,所以前2个couts工作完美。但是当我访问的矢量的内容,它只是崩溃,并给出一个分割错误错误。任何人都知道为什么?
in this case, nodes[0]'s string is "G" and is pointing to 2 other nodes, so the first 2 couts are working perfectly. But when I access the vector's contents it just crashes and gives a segmentation fault error. Anyone know why?
推荐答案
在 add_arc
参数 a
,然后在函数退出时被销毁 - 因此你有未定义的行为。
In add_arc
you are storing the address of the parameter a
, which is then destroyed when the function exits - so you have undefined behaviour.
当你调用 nodes.push_back()
时,也会复制节点,这将导致你很多的悲伤。
You're also copying nodes when you call nodes.push_back()
, which is going to cause you a lot of grief.
你将需要停止复制或写一个正确的复制构造函数(然后遵循3或5的规则)。
You are going to need to either stop copying or write a proper copy constructor (and then follow the rule of 3, or 5).
这篇关于在向量中访问指针的成员函数时的分段故障的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!