使用 nullptr 终止迭代器
Terminate an iterator with a nullptr
我试图通过实现各种常见的数据结构来提高我对C++的了解。 我从一个链接列表开始。 我希望能够使用它使用基于范围的 for 循环。 我阅读了这个问题,然后基于此示例代码实现。
我的问题是我目前正在用一个nullptr
终止我的链表;最终ListNode
的数据成员next_
设置为nullptr
。 因此,我在LinkedList<T>::end()
函数中将nullptr
作为迭代器构造函数中的参数传递,我认为它应该正确终止函数。 它按预期工作;当我重载<<
它会正确地将内容写入流。
不幸的是,它这样做有一些内存错误(在使用DrMemory时看到(。 这是因为有一行不正确地尝试从nullptr
中提取数据成员(代码和说明如下(。 但是,为nullptr
添加比较以避免这种情况失败(见下文(。 最后,由于重载(不(相等运算符需要它们接受引用,因此在列表的最后一个元素中传递对nullptr
的引用。 根据这个答案,这是一个很大的诺诺。 我如何修复当前的实现,或返工我的实现以避免nullptr
?
我正在使用 mingw32-g++ 编译器 4.8.1 版进行编译,如下所示
$ mingw32-g++ -g -Wall -Werror -Wextra -pedantic -std=gnu++11 -c <cpp file>
$ mingw32-g++ -o main <object files>
然后我在DrMemory中使用以下命令在DrMemory中运行它
$ drmemory -- main
在DrMemory中运行它会得到我的输出
UNINITIALIZED READ: reading register edx
# 0 ConstListIterator<>::operator!= [structures/listiterator.hpp:167]
# 1 _fu0___ZSt4cout [C:Usersdannn_000documentsgithubdatastructures/main.cpp:10]
# 2 __mingw_CRTStartup
# 3 mainCRTStartup
# 4 ntdll.dll!RtlInitializeExceptionChain +0x8e (0x77e6b5af <ntdll.dll+0x5b5af>)
# 5 ntdll.dll!RtlInitializeExceptionChain +0x59 (0x77e6b57a <ntdll.dll+0x5b57a>)
Note: @0:00:00.738 in thread 9500
Note: instruction: cmp %edx %eax
根据 DrMemory 的输出,问题出在重载运算符!=
ConstListIterator
中的实现中,查看我们可以清楚地看到问题行:
return current_ != rhs.current_;
它将在到达最后一个节点(nullptr
(时执行未初始化的读取。 我心想"哦,很容易解决"并将其更改为
if (rhs == nullptr)
return current_ != nullptr;
return current_ != rhs.current_;
编译时给出错误
mingw32-make : In file included from structures/list.hpp:16:0,
At line:1 char:1
+ mingw32-make main 2> t.txt
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (In file include.../list.hpp:16:0,:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
from structures/linkedlist.hpp:16,
from main.cpp:1:
structures/listiterator.hpp: In instantiation of 'bool ConstListIterator<T>::operator!=(const ConstListIterator<T>&) [with T =
int]':
main.cpp:10:16: required from here
structures/listiterator.hpp:167:10: error: no match for 'operator==' (operand types are 'const ConstListIterator<int>' and
'std::nullptr_t')
if (rhs == nullptr)
^
structures/listiterator.hpp:167:10: note: candidate is:
structures/listiterator.hpp:153:6: note: bool ConstListIterator<T>::operator==(const ConstListIterator<T>&) [with T = int] <near
match>
bool ConstListIterator<T>::operator==(const ConstListIterator<T>& rhs)
^
structures/listiterator.hpp:153:6: note: no known conversion for implicit 'this' parameter from 'const
ConstListIterator<int>*' to 'ConstListIterator<int>*'
structures/listiterator.hpp:168:19: error: no match for 'operator!=' (operand types are 'ListNode<int>*' and 'const
ConstListIterator<int>')
return current_ != rhs;
^
mingw32-make: *** [main.o] Error 1
因此,我继续添加一个成员函数,该函数可以将ConstListIterator
与std::nullptr_t
进行比较,但是一旦添加该函数,我就会收到一个新错误
mingw32-make : In file included from structures/list.hpp:16:0,
At line:1 char:1
+ mingw32-make main 2> t.txt
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (In file include.../list.hpp:16:0,:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
from structures/linkedlist.hpp:16,
from main.cpp:1:
structures/listiterator.hpp: In instantiation of 'bool ConstListIterator<T>::operator!=(const ConstListIterator<T>&) [with T =
int]':
main.cpp:10:16: required from here
structures/listiterator.hpp:182:10: error: no match for 'operator==' (operand types are 'const ConstListIterator<int>' and
'std::nullptr_t')
if (rhs == nullptr)
^
structures/listiterator.hpp:182:10: note: candidates are:
structures/listiterator.hpp:156:6: note: bool ConstListIterator<T>::operator==(const ConstListIterator<T>&) [with T = int] <near
match>
bool ConstListIterator<T>::operator==(const ConstListIterator<T>& rhs)
^
structures/listiterator.hpp:156:6: note: no known conversion for implicit 'this' parameter from 'const
ConstListIterator<int>*' to 'ConstListIterator<int>*'
structures/listiterator.hpp:162:6: note: bool ConstListIterator<T>::operator==(std::nullptr_t&) [with T = int;
std::nullptr_t = std::nullptr_t]
bool ConstListIterator<T>::operator==(std::nullptr_t& rhs)
^
structures/listiterator.hpp:162:6: note: no known conversion for argument 1 from 'std::nullptr_t' to
'std::nullptr_t&'
structures/listiterator.hpp:183:19: error: no match for 'operator!=' (operand types are 'ListNode<int>*' and 'const
ConstListIterator<int>')
return current_ != rhs;
^
mingw32-make: *** [main.o] Error 1
这是我代码的(简化(版本。 我已经删除了许多我认为与此代码无关的成员函数,并且我已经尽力删除它们在代码本身中的用法。
Listnode.hpp
#ifndef LISTNODE_HPP
#define LISTNODE_HPP 1
template <typename T>
struct ListNode {
public:
ListNode() = delete;
ListNode(T value);
ListNode<T>* getNext();
void setNext(ListNode<T>* node);
T& getValue();
const T& getCValue() const;
void setValue(T value);
private:
T value_;
ListNode<T>* next_;
};
// Standard implementations of all member functions.
#endif
我有另一个文件"list.hpp",其中包含我的LinkedList
类的抽象基类,所有成员函数都是纯虚函数。 为简洁起见,排除在外。 此文件还具有用于处理非 const 迭代器的适当成员函数,但是这些函数或多或少是相同的,并且不是此处使用的函数,并且因此而被排除。
链接列表.hpp
#ifndef LINKEDLIST_HPP
#define LINKEDLIST_HPP 1
#include <cstddef>
#include "listnode.hpp"
#include "list.hpp"
#include "listiterator.hpp"
#include "../exceptions.hpp"
template <typename T>
class LinkedList : public List<T>
{
public:
LinkedList();
LinkedList(T* arr, std::size_t length);
~LinkedList();
ConstListIterator<T> begin() const;
ConstListIterator<T> end() const;
private:
std::size_t numElements_;
ListNode<T>* head_;
ListNode<T>* tail_;
};
template <typename T> inline LinkedList<T>::LinkedList() :
numElements_(0), head_(nullptr), tail_(nullptr) {
}
template <typename T> inline LinkedList<T>::LinkedList(
T* arr, std::size_t length) :
numElements_(length), head_(nullptr), tail_(nullptr) {
head_ = new ListNode<T>(arr[0]);
ListNode<T>* current = nullptr;
ListNode<T>* next = nullptr;
current = head_;
for (std::size_t i = 1; i < length; ++i) {
next = new ListNode<T>(arr[i]);
current->setNext(next);
current = next;
}
tail_ = current;
}
template <typename T> inline LinkedList<T>::~LinkedList()
{
ListNode<T>* current = head_;
ListNode<T>* next = nullptr;
for (std::size_t i = 0; i < numElements_; ++i) {
next = current->getNext();
delete current;
current = next;
}
}
template <typename T> inline
ConstListIterator<T> LinkedList<T>::begin() const
{
return ConstListIterator<T>(head_);
}
template <typename T> inline
ConstListIterator<T> LinkedList<T>::end() const
{
return ConstListIterator<T>(nullptr);
}
#endif
最后,我的迭代器的实现。 同样,我排除了这些的非常量版本(原因与上述相同(。
listiterator.hpp
#ifndef LISTITERATOR_HPP
#define LISTITERATOR_HPP 1
#include <iterator>
#include "listnode.hpp"
template <typename T>
class ConstListIterator
{
public:
typedef std::forward_iterator_tag iterator_category;
ConstListIterator() = delete;
ConstListIterator(ListNode<T>* node);
ConstListIterator operator++();
ConstListIterator operator++(int);
const ListNode<T>& operator*();
const ListNode<T>* operator->();
bool operator==(const ConstListIterator<T>& rhs);
bool operator==(std::nullptr_t& rhs);
bool operator!=(const ConstListIterator<T>& rhs);
private:
ListNode<T>* current_;
};
template <typename T> inline
ConstListIterator<T>::ConstListIterator(ListNode<T>* node) :
current_(node) {
}
template <typename T> inline
ConstListIterator<T> ConstListIterator<T>::operator++()
{
current_ = current_->getNext();
return *this;
}
template <typename T> inline
ConstListIterator<T> ConstListIterator<T>::operator++(int)
{
current_ = current_->getNext();
return *this;
}
template <typename T> inline
const ListNode<T>& ConstListIterator<T>::operator*()
{
return *current_;
}
template <typename T> inline
const ListNode<T>* ConstListIterator<T>::operator->()
{
return current_;
}
template <typename T> inline
bool ConstListIterator<T>::operator==(const ConstListIterator<T>& rhs)
{
return current_ == rhs.current_;
}
template <typename T> inline
bool ConstListIterator<T>::operator!=(const ConstListIterator<T>& rhs)
{
return current_ != rhs.current_;
}
#endif
以及我用来运行这一切的文件
主.cpp
#include "structures/linkedlist.hpp"
#include <iostream>
int main()
{
LinkedList<int> list;
list.append(1);
for (auto i : list)
std::cout << i << std::endl;
return 0;
}
首先,由于您打算使用 STL 算法,因此最好从 std::iterator 派生。
一些迭代器声明是错误的,这是修复:
ConstListIterator() : current_(nullptr) {} // basically end() iterator
ConstListIterator(ListNode<T>* node);
ConstListIterator& operator++();
ConstListIterator operator++(int);
const ListNode<T>& operator*() const;
const ListNode<T>* operator->() const;
bool operator==(const ConstListIterator<T>& rhs) const;
bool operator!=(const ConstListIterator<T>& rhs) const;
后缀增量也不正确:
template <typename T> inline
ConstListIterator<T> ConstListIterator<T>::operator++(int)
{
auto old = current_;
current = current_->getNext()
return ConstListIterator<T>(old);
}
至于你的问题:运算符 != 与它无关,因为你正在比较指向底层对象的指针(所以它们是否为 nullptr 并不重要(。
从 DrMemory 的输出来看(我从未使用过它,但我假设 #5-#0 是调用堆栈(,有两种可能性:
- 您的<<操作员有问题
- DrMemory有问题(因为它在<<内部的寄存器比较中抱怨(。或者它可能是正确的,问题是增量不正确的副作用。
- 使用std::multimap迭代器创建std::list
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++中带有List类的迭代器Segfault
- 如何在c++迭代器类型中包装std::chrono
- 集合上的输出迭代器:assign和increment迭代器
- Boost Spirit,获取迭代器内部语义动作
- 对于set上的循环-获取next元素迭代器
- 为什么output_editor Concept不需要output_e迭代器标记
- c++17文件系统::recursive_directory迭代器()在mac上没有给出这样的目录,但在windows上
- 使用迭代器时如何访问对象在向量中的位置?
- std::vector::迭代器是否可以合法地作为指针
- 跟随整数索引列表的自定义类迭代器
- 不明白迭代器,引用和指针失效,一个例子
- 我可以使用反向迭代器作为ForwardIt吗
- ESP8266单片机矢量迭代器的C++问题
- std::使用迭代器映射查找距离,程序不会终止
- 使用 nullptr 终止迭代器
- 为什么需要它!=obj.end() 尽管每个迭代器都应该知道自己何时终止
- c++boost迭代器抛出断言,程序终止
- 在处理迭代器时被信号SIGSEGV(地址边界错误)终止