【问题标题】:std::pair of std::string and custom class fails to copy on std::map::insert(std::make_pair(string, class))std::pair 的 std::string 和自定义类无法复制到 std::map::insert(std::make_pair(string, class))
【发布时间】:2011-10-15 05:55:56
【问题描述】:

这个错误:

error C2678: binary '=' : no operator found which takes a left-hand operand of type 'const std::string' (or there is no acceptable conversion)  c:\program files (x86)\microsoft visual studio 10.0\vc\include\utility  216

出现在这个函数的唯一一行:

void Animation::AddAnimation(std::string name, AnimationFrameSet& animation) {
    _animations.insert(std::make_pair(name, animation));
}

_animationsstd::map<std::string, AnimationFrameSet>

AnimationFrameSet 声明了一个 operator=(...) 和一个复制构造函数,但奇怪的是,编译器说它在尝试复制 const std::string... 时失败了,即使字符串甚至没有作为const

我一辈子都想不通(甚至不记得!:P)为什么这是/应该抛出/抛出错误。

谢谢。

编辑

我有点困惑为什么这不起作用的原因是不同的类使用非常相似的实现并且它不会抛出错误:

BITMAP* BitmapCache::GetBitmap(std::string filename) {
    //Return NULL if a bad filename was passed.
    if(filename.empty()) return NULL;
    if(exists(filename.c_str()) == false) return NULL;

    //Reduce incorrect results by forcing slash equality.
    filename = fix_filename_slashes(&filename[0]);

    //Clean the cache if it's dirty.
    CleanCache();

    //Search for requested BITMAP.
    MapStrBmpIter _iter = _cache.find(filename);

    //If found, return it.
    if(_iter != _cache.end()) return _iter->second;

    //Otherwise, create it, store it, then return it.
    BITMAP* result = load_bmp(filename.c_str(), NULL);
    if(result == NULL) return NULL;
    /*Similar insert line, a non-const std::string that was passed in is passed to a std::make_pair(...) function*/
    _cache.insert(std::make_pair(filename, result));
    return result;
}

类型定义:

typedef std::map<std::string, BITMAP*> MapStrBmp;
typedef MapStrBmp::iterator MapStrBmpIter;

【问题讨论】:

  • 你能告诉我们operator=吗?如果您明确指定 make_pair 的类型参数会发生什么?
  • 你是否包含了“#include ”?
  • 也尝试提供一个给出相同问题的最小代码
  • 基于标题路径,我很确定 Visual Studio 2010 打印出的不仅仅是那一行。您可能希望将其包含在您的问题中。

标签: c++ insert std-pair


【解决方案1】:

这失败的原因是因为您使用的 std::map 容器需要一个 const 值作为键值。

查看 std::map here 的文档。

例子:

class TestClass
{
};

std::map< const std::string, TestClass > myMap;
std::pair< const std::string, TestClass > firstElement = std::make_pair("test", TestClass() );
myMap.insert( firstElement );

【讨论】:

    【解决方案2】:

    由于_animationsstd::map,请尝试使用另一种插入方法,例如:

    _animations[name] = animation;
    

    但更重要的是要检查 AnimationFrameSet 类是否具有有效的复制构造函数和赋值运算符。如果不是,您可能需要使用智能指针类,例如:

    typedef std::shared_ptr<AnimationFrameSet> AnimationFrameSetPtr;
    

    那么地图将是:

    std::map<std::string, AnimationFrameSetPtr>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-29
      • 1970-01-01
      • 2013-05-28
      • 1970-01-01
      • 1970-01-01
      • 2011-06-06
      相关资源
      最近更新 更多