gpt4 book ai didi

c++ - 一个函数调用改变了它的参数

转载 作者:行者123 更新时间:2023-11-30 01:13:57 25 4
gpt4 key购买 nike

我有以下代码:

#include <iostream>

using namespace std;

template <class T>
class Iterator;

template <class T>
class List;

template <class T>
class List {
public:
struct Node;
Node* first;
friend class Iterator<T>;

List() :
first(NULL) { }

Iterator<T> begin() {
cout << first->data << endl;
return Iterator<T>(*this, first); // <--- problematic call
}

void insert(const T& data) {
Node newNode(data, NULL);
first = &newNode;
}
};

template <class T>
struct List<T>::Node {
private:
T data;
Node* next;

friend class List<T>;
friend class Iterator<T>;

Node(const T& data, Node* next) :
data(data), next(next) { }
};

template <class T>
class Iterator {
private:
const List<T>* list;
typename List<T>::Node* node;

friend class List<T>;

public:
Iterator(const List<T>& list, typename List<T>::Node* node) {
cout << node->data << endl;
}
};

int main() {
List<int> list;
list.insert(1);
list.begin();

return 0;
}

首先,我将节点数据设置为“1”(int)。在我将它传递给 Iterator 构造函数之后,它改变了 node->data 的值。

我在调用前后打印了node->data:

1
2293232

我猜 2293232 是某物的地址,但我找不到发生这种情况的原因。

最佳答案

当你写作时

    void insert(const T& data) {
Node newNode(data, NULL);
first = &newNode;
}

然后:

  1. 你在栈上创建一个对象

  2. 将一些(更多)持久指针指向它的地址

  3. 当它超出范围时销毁它

所以你只剩下垃圾了。

关于c++ - 一个函数调用改变了它的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30879640/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com