返回成员变量时,为什么在函数内外得到不同的结果?

asr*_*att 0 c++ pointers return function vector

当我尝试在函数内部打印成员变量时,它会给出我想要的结果.但是,如果我返回此成员变量然后尝试在main中访问它,它会给我一个不同的结果.为什么会这样?

这是我的代码的样子:

Node.h:

#include <cstddef>
#include <vector>
#include <iostream>

using namespace std;

class Node{
 public:
    int v;
    Node * parent;
    Node(int I);
    Node(int I,Node * p);
    vector<Node*> myfun();
}
Run Code Online (Sandbox Code Playgroud)

Node.cpp:

Node::Node(int I){
    v = I;
    parent = NULL;
}

Node::Node(int I,Node * p){
    v = I;
    parent = p;
}

vector<Node*> Node::myfun(){
    vector<Node*> myvec;

    Node next1(1,this);
    myvec.push_back(&next1);

    Node next2(2,this);
    myvec.push_back(&next2);

    cout << myvec[0]->v << endl; // prints out "1"
    cout << myvec[1]->v << endl; // prints out "2"

    return(myvec);
}
Run Code Online (Sandbox Code Playgroud)

main.cpp中:

#include "Node.h"

int main(){
    vector<Node*> myvec;
    Node init(0);
    myvec = init.myfun();

    cout << myvec[0]->v << endl; // prints out garbage
    cout << myvec[1]->v << endl; // prints out garbage

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Vic*_*voy 6

因为在你的Node::myfun()next1和你的next2变量都被破坏(它们不再存在)在方法的最后.因此,您将返回指向不再存在的对象的指针.这样的指针称为悬空指针,取消引用悬空指针是Undefined Behavior.

  • @awilds你正在推送他们的地址,这是堆栈地址.使用`new`. (2认同)