簡體   English   中英

插入std :: map時的常數問題

[英]constness issue when inserting into an std::map

嘗試將一對插入地圖時遇到常數問題。 編譯器錯誤是:

              c:\program files (x86)\microsoft visual studio 11.0\vc\include\xutility(2089) : see reference to function template instantiation 'std::pair<_Ty1,_Ty2> &std::pair<_Ty1,_Ty2>::operator =(const std::pair<_Ty1,_Ty2> &)' being compiled
1>          with
1>          [
1>              _Ty1=const Assets::AssetId,
1>              _Ty2=std::shared_ptr<Assets::Material>
1>          ]
1>          c:\fusionengine\meshgl.cpp(85) : see reference to class template instantiation 'std::pair<_Ty1,_Ty2>' being compiled
1>          with
1>          [
1>              _Ty1=const Assets::AssetId,
1>              _Ty2=std::shared_ptr<Assets::Material>
1>          ]

導致錯誤的行是:

m_materials.insert( MaterialsMap::value_type(pMaterial->AssetId(), pMaterial) );

m_materials映射聲明如下:

typedef std::map< Assets::AssetId, std::shared_ptr<Material> > MaterialsMap;    
typedef std::pair< Assets::AssetId, std::shared_ptr<Material> > MtlPair;

MaterialsMap  m_materials;

錯誤1錯誤C2166:左值指定const對象c:\\程序文件(x86)\\ Microsoft Visual Studio 11.0 \\ vc \\ include \\ utility 114

誰能解釋我如何解決此問題?

在這個問題上,我扯掉了頭發,我大概花了一個星期或一個星期的時間在上面。 幸運的是,它對項目路線圖並不重要,因此它並沒有阻止其繼續進行。

這個問題與編譯器無關,盡管錯誤報告可以增強功能,但是我意識到,模板(和STL)代碼始終是一個問題。

因此,我在operator =重載中有一個std :: copy來將一個映射的內容復制到另一個。 我幾乎不知道這是一個禁忌。

我終於通過逐行和逐功能地重新構建整個類來找出問題所在,以便隔離問題區域。

然后,通過檢查問題區域並進行谷歌搜索,stackoverflow對此問題和答案進行了補救。

盡管以下語句是非法的,但在VS2012 IDE中不會將其突出顯示為錯誤,編譯器也不會將其標識為問題語句。

std::copy( map1.begin(), map1.end(), map2.begin() );

正如前面突出顯示的SO答案所述,正確的方法是使用插入語句:

map2.insert( map1.begin(), map1.end() );

我希望這可以幫助某人:)

這段代碼可以用GCC很好地編譯

#include <map>
#include <memory>
using namespace std;

typedef int AssetId;
struct Material {
    int _id;
    Material(int id) : _id(id) {}
    int AssetId() const { return _id; }
};
typedef std::map< AssetId, std::shared_ptr<Material> > MaterialsMap;    

MaterialsMap  m_materials;

int main() {
    std::shared_ptr<Material> pMaterial(new Material(42));
    m_materials.insert( MaterialsMap::value_type(pMaterial->AssetId(), pMaterial) );
}

您的示例不完整或錯誤,或者這是MSVC2012標准庫的實現中的錯誤。 不應在以上代碼中調用operator=

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM