1

使用 VS 2008,目标环境是带有 ARM 处理器的 Windows CE,如果这有所不同的话。我知道我们使用的编译器也有点过时了......

我遇到的基本问题是我正在尝试为我编写的地图包装器制作自己的迭代器,并且重载 operator->() 给我带来了麻烦。这是给我带来问题的代码:

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

我知道通常返回一个 const 变量并没有什么意义,但我似乎无法弄清楚如何以一种让程序的其余部分在不这样做的情况下保持 const 正确的方式做到这一点。

我得到的错误是这样的:

错误 C2440:'return':无法从 'const std::pair<_Ty1,_Ty2> *' 转换为 'const std::pair<_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。

我已经为此挠头太久了。请让我知道,如果你想出任何办法。谢谢!

4

1 回答 1

3

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->());
}
于 2012-03-21T20:15:12.217 回答