从成员函数返回列表时导致分段错误的原因是什么?

Var*_*lex 0 c++ netbeans segmentation-fault

我在Windows 8上使用Netbeans 7.4和cygwin编译器.我得到了分段错误,我找不到它的来源.

Node.h

class Node {
public:

    // Getters & Setters
    inline std::list<Node*> getAdjL() const { return adjacentList; }

    // Member Functions
    void printAdj() const;

private:
    unsigned id;
    std::list<Node*> adjacentList;
}
Run Code Online (Sandbox Code Playgroud)

我还有print函数作为成员函数(在外部调用表单时工作正常):

Node.cpp

void Node::printAdj() const {
    std::cout << "Adjacent list of node with id: " << id << std::endl;
    for(std::list<Node*>::const_iterator it = adjacentList.begin();
            it != adjacentList.end(); ++it){
        std::cout << (*it)->getId() << "\t";
    }
    std::cout << std::endl << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

main.cpp中

Node* u = NULL;
while( some condition ){
    u = smallest(nodes);    // smallest distance & un-visited node

    list<Node*>::const_iterator iter = u->getAdjL().begin();
    cout << endl << "size: " << u->getAdjL().size() << endl;
    cout << "printing info" << endl;
    u->printAdj();                     // works just fine (member function)
    cout << (*iter)->getId() << endl;  // segmentation fault
Run Code Online (Sandbox Code Playgroud)

产量

size: 1
printing info
Adjacent list of node with id: 0
9


RUN FAILED (exit value 1, total time: 2s)
Run Code Online (Sandbox Code Playgroud)

当我尝试调试时,我被提示我有SIGSEGV(分段错误).是什么导致这个?

注意:我相信我只包含相关部分,但如果您需要额外的代码,请发表评论.

spi*_*orm 5

这种方法

inline std::list<Node*> getAdjL() const { return adjacentList; }
Run Code Online (Sandbox Code Playgroud)

返回adjacentList作为临时对象的副本,在此行之后立即销毁:

list<Node*>::const_iterator iter = u->getAdjL().begin();
Run Code Online (Sandbox Code Playgroud)

所以你iter是一个被破坏的对象的迭代器,并指向垃圾

您可能希望让getter返回对值的引用

inline const std::list<Node*>& getAdjL() const
Run Code Online (Sandbox Code Playgroud)

这应该会使事情奏效.或者存储getAdjL()某处返回的值