如何避免使用临时变量的地址
How to avoid taking address of a temporary variable?
我的代码目前设置的方式,我觉得我必须在分割错误和使指针指向临时对象之间做出选择。代码如下:
#include <memory>
#include <cstddef>
#include <iostream>
template <typename T> class Node;
template <typename T> class List {
public:
typedef std::size_t size_type;
typedef T value_type;
typedef T& reference;
typedef const T& const_reference;
class iterator {
public:
iterator() {
isNull = true;
}
iterator(const T val) {
isNull = false;
data = val;
prev = this;
next = &iterator(); #PROBLEMATIC LINE
}
iterator operator++() {
if(this->next->isNull)
return iterator();
iterator old_it = *this;
this->prev = &old_it;
this->next = this->next->next;
this->data = this->next->data;
return *this;
}
T& operator*() {
return data;
}
iterator* next;
iterator* prev;
T data;
bool isNull;
};
List() {
_begin = iterator();
_end = _begin;
}
List(size_type n, T val) {
_begin = iterator(val);
_end = *(_begin.next);
_end.prev = &_begin;
}
void push_back(T val) {
iterator temp = iterator();
_end.data = val;
_end.next = &temp;
temp.prev = &_end;
_end = temp;
}
iterator begin() {return _begin;}
iterator end() {return _end;}
private:
iterator _begin;
iterator _end;
};
int main() {
List<int> derp= List<int>(3,3);
List<int>::iterator i = derp.begin();
std::cout << *i;
derp.push_back(4);
std::cout << i.data;
++i;
std::cout << *i;
}
上面的代码接受一个临时变量的地址。当我从
更改有问题的行时next = &iterator();
*next = iterator();
代码得到分段错误,但我不知道为什么。任何帮助都会很感激。以及您可能碰巧注意到的代码中的任何严重缺陷。
第一个错误是因为您必须找到一个地方来存储创建的对象,然后才能存储指向它的指针。临时对象会消失——你必须把它放在某个地方。
第二个错误是因为必须先初始化指针才能解引用它。它必须指向某个东西
但是有一个概念上的问题。迭代器是一种逻辑上相当于指针的对象。指针到迭代器相当于指针到指针。因此,next和prev成员要么是指针到节点,要么是迭代器,而不是指针到迭代器。
如果你能让你的代码按照你想要的方式工作,其他的问题就会消失。我不太明白整件事的重点,所以我不能告诉你怎么做
*next = iterator()导致分段错误,因为您使用了未初始化的指针。Next = &iterator()也很糟糕。临时对象
相关文章:
- 附加调试器并以编程方式获取变量地址 Visual Studio
- 变量地址的运算符[]是如何工作的
- C 给出了一个字符串列表,如何从类中获取各个变量地址
- 从函数返回变量地址时如何修复"与局部变量关联的堆栈内存地址"?
- 获取封装在命名空间中的静态变量地址
- 为什么分配的变量地址之间相差 16 个字节?
- 为什么在循环中定义的变量地址在每次迭代中都保持不变
- 是否可以使用指向语句中声明的变量地址的指针"if"
- 字符串从变量(&变量)地址的长度 - 嵌入式C
- 汇编:C++堆栈变量地址不同/错误?
- x 在变量地址中的意义是什么?
- 在哪里放置 HW BP 以捕获全局变量地址损坏
- C++变量地址不匹配
- 重载 std::ostream 运算符<<未调用,stream 获取变量地址而不是对象
- std矢量包含指针和变量地址.清理
- 注册变量地址
- 使用内联程序集获取变量地址
- 如果用调试信息编译,则通过其名称获取全局变量地址
- 如何在Visual Studio中复制变量地址
- 当堆栈内存中的变量地址分配给数据段或堆内存中的指针时,是否有任何错误?