取消引用迭代器会导致'can not convert'错误,而它似乎不应该

dereferencing iterator causes 'can not convert' error when it seems it shouldn't

本文关键字:错误 不应该 convert can 迭代器 引用 取消 not      更新时间:2023-10-16

使用VS 2008,目标环境是带有ARM处理器的Windows CE(如果有区别的话)。我知道我们使用的编译器也有点过时了。。。

我遇到的基本问题是,我试图为我编写的映射包装器制作自己的迭代器,而重载运算符->()给我带来了麻烦。这是一段给我带来问题的代码:

const pair<wstring, PropertyMap*>* ObjectMapIterator::operator->() const
{
    return &*m_MapIter;
}

我知道通常返回常量变量是没有意义的,但我似乎不知道如何在不这样做的情况下让程序的其余部分保持常量正确。

我得到的错误是:

错误C2440:"return":无法从"const"转换std::对&lt_Ty1,_Ty2>*'到'conststd::对&lt_Ty1,_Ty2>*'

这个迭代器的头看起来像这样:

class ObjectMapIterator
{
public:
    ObjectMapIterator(const ObjectMap& rObjectMap);
    const ObjectMapIterator& operator++(int rhs);
    std::pair<std::wstring, PropertyMap*> operator*() const;
    const std::pair<std::wstring, PropertyMap*>* operator->() const;
    bool isDone() const;
private:
    const std::map<std::wstring, PropertyMap*>* m_pPropertyMaps;
    std::map<std::wstring, PropertyMap*>::const_iterator m_MapIter;
};

正如您所看到的,m_MapIter和重载运算符的返回值是相同的。。。我从项目的这一部分的.h和.cpp文件中取出了所有的const语句,并用同样的错误重新编译,所以我认为这不是问题。

如果我改为这样做,程序将编译:

const pair<wstring, PropertyMap*>* ObjectMapIterator::operator->() const
{
    const pair<wstring, PropertyMap*>* returnVal = new pair<wstring, PropertyMap*>(*m_MapIter);
    return returnVal;
}

我知道这样做会导致内存泄漏,我并不是为了节省发布空间而把它放在智能指针中。

以下是整个.cpp文件,以防您发现相关内容:

#include "stdafx.h"
#include "ObjectMap.h"
using namespace std;
ObjectMapIterator::ObjectMapIterator(const ObjectMap& rObjectMap)
    :m_pPropertyMaps(&(rObjectMap.m_PropertyMaps)),
     m_MapIter(m_pPropertyMaps->begin())
{}
const ObjectMapIterator& ObjectMapIterator::operator++(int rhs)
{
    if(m_MapIter != m_pPropertyMaps->end())
    {
        m_MapIter++;
        return *this;
    }
    else
    {
        return *this;
    }
}
pair<wstring, PropertyMap*> ObjectMapIterator::operator*() const
{
    return *m_MapIter;
}
const pair<wstring, PropertyMap*>* ObjectMapIterator::operator->() const
{
    return &*m_MapIter;
}
bool ObjectMapIterator::isDone() const
{
    return m_MapIter == m_pPropertyMaps->end();
}

ObjectMapIterator定义位于ObjectMap.h文件中。所以我不会忘记包含ObjectMapIterator。

我已经为这件事挠头太久了。如果你想知道什么,请告诉我。谢谢

std::map::const_iterator返回一个临时的,而不是引用,所以您试图获取该临时的地址并返回它。

为什么不简单地按值返回pair

std::pair<std::wstring, PropertyMap*>* ObjectMapIterator::operator->() const
{
    return *m_MapIter;
}

实际上,如果您的操作员将返回std::map::const_iterator::pointerstd::map::const_iterator::operator->()做到了,一切都会好起来的:

std::map<std::wstring, PropertyMap*>::const_iterator::pointer operator->() const
{
return &*m_MapIter;
}

此外,就std::map::const_iterator::operator->()返回的值是实现定义的而言,使用可能会更好

auto operator->() const -> decltype(m_MapIter.operator->())
{
return (m_MapIter.operator->());
}