如何避免使用临时变量的地址

How to avoid taking address of a temporary variable?

本文关键字:变量 地址 何避免      更新时间:2023-10-16

我的代码目前设置的方式,我觉得我必须在分割错误和使指针指向临时对象之间做出选择。代码如下:

#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()也很糟糕。临时对象