在迭代器中使用C ++后递增运算符重载(使用-Wall -Werror进行编译) [英] C++ post-increment operator overload in iterators (compiling with -Wall -Werror)

查看:357
本文介绍了在迭代器中使用C ++后递增运算符重载(使用-Wall -Werror进行编译)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在为b-tree创建自己的迭代器,而且我仍然坚持在没有编译器抱怨的情况下实现后递增运算符。



错误消息如下,并且是预期的(因为我正在做错误消息说的)

  cc1plus:warnings被视为错误
错误:对局部变量'temp'的引用返回

使用-Wall和-Werror标签编写函数,所以希望有人能够帮助我解决这个问题。



这里是函数:

  template< typename T> btree_iterator< T> btree_iterator< T> :: operator ++(int){

btree_iterator< T> temp(* this);
pointee_ = pointee _-> nextNode();
return temp;
}

我看了一下,我只能找到例子



每当我以前遇到这样的问题时,我都会重新载入我返回的对象, t临时。但是由于这是一个迭代器,如果我这样做,我将无法释放内存后,因此有内存泄漏。



如果任何人能够帮助我,这将是非常感谢!



请注意。

 错误:引用本地变量'temp '返回

在函数中,返回 temp ,这是临时对象。



也许你需要返回一个副本(因为你不想使用 new )。因此,

  template< typename T> btree_iterator< T> btree_iterator< T> :: operator ++(int){

您可能需要

  //注意缺少的`&`............... vv 
template< typename T> btree_iterator< T> btree_iterator< T> :: operator ++(int){


I'm currently creating my own iterator for a b-tree, and I'm stuck on how to implement the post-increment operator without the compiler complaining.

The error message is as follows, and is expected (since I am doing exactly what the error message says)

cc1plus: warnings being treated as errors
error: reference to local variable 'temp' returned

I am required to write the function with the -Wall and -Werror tags, so hopefully someone is able to help me with a solution around that.

Here is the function:

template <typename T> btree_iterator<T>& btree_iterator<T>::operator++(int) {

  btree_iterator<T> temp(*this);
  pointee_ = pointee_->nextNode();
  return temp;
}

I had a look around, and I was only able to find examples of people implementing the operator exactly how I am at the moment.

Whenever I previously had a problem like this, I 'new'ed the object I was returning so that it wasn't temporary any more. But since this is an iterator, if I did that, i won't be able to free the memory afterwards, and thus having memory leaks.

If anyone is able to help me out, that would be greatly appreciated! Please let me know if there is anything else about my design that would help you understand the problem.

Regards.

解决方案

The error is clear enough -

error: reference to local variable 'temp' returned

In your function, you return reference to temp, which is temporary object.

Maybe you need to return a copy(as you don't want to use new ). So, instead

template <typename T> btree_iterator<T>& btree_iterator<T>::operator++(int) {

you maybe need

// note the missing `&`...............vv
template <typename T> btree_iterator<T> btree_iterator<T>::operator++(int) {

这篇关于在迭代器中使用C ++后递增运算符重载(使用-Wall -Werror进行编译)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆