我有以下以pair作为键的映射用法,并且它出现段错误。 有任何想法吗?
我简化了示例以帮助提高可靠性。 错误如下代码:
#include <map>
#include<iostream>
#include<string>
using namespace std;
class A
{
public:
map<pair<string, string>, string* > m;
string str;
A():str("sdfsd")
{
m[make_pair("aa","bb")]=&str;
}
void foo()
{
map<pair<string, string>, string*>::iterator iter =m.begin();
cout<<"In A::foo:\n";
for(; iter!=m.end(); iter++)
{
pair<string, string> keys=iter->first;
cout<<"map and test = "<<str<<" and "<<*iter->second<<endl;
}
}
};
int main()
{
A a;
a.foo();
}
在核心文件中:
#0 0x0066f6c7 in std::string::_Rep::_M_grab () from /usr/lib/libstdc++.so.5 #1 0x0066f80c in std::basic_string, std::allocator >::basic_string () from /usr/lib/libstdc++.so.5 #2 0x087e1e69 in pair (this=0xbfff7070, _ctor_arg=@0x9c087d0) at (pair keys=iter->first;)
I simpled the example to help with reability. Error follows the code:
#include <map>
#include<iostream>
#include<string>
using namespace std;
class A
{
public:
map<pair<string, string>, string* > m;
string str;
A():str("sdfsd")
{
m[make_pair("aa","bb")]=&str;
}
void foo()
{
map<pair<string, string>, string*>::iterator iter =m.begin();
cout<<"In A::foo:\n";
for(; iter!=m.end(); iter++)
{
pair<string, string> keys=iter->first;
cout<<"map and test = "<<str<<" and "<<*iter->second<<endl;
}
}
};
int main()
{
A a;
a.foo();
}
In core file:
#0 0x0066f6c7 in std::string::_Rep::_M_grab () from /usr/lib/libstdc++.so.5 #1 0x0066f80c in std::basic_string, std::allocator >::basic_string () from /usr/lib/libstdc++.so.5 #2 0x087e1e69 in pair (this=0xbfff7070, _ctor_arg=@0x9c087d0) at (pair keys=iter->first;)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是编译器的问题吗? 它看起来像是一些奇怪的编译器优化,特别是当别名 iter->first 产生差异时。
刚刚发布到在线编译器 http://codepad.org/ZhYvtj9v
它给出了正确的结果,没有段错误。
Is it a compiler problem? It looks like some weird compiler optimisation, especially when aliasing iter->first makes the difference.
Just posted onto online compiler at http://codepad.org/ZhYvtj9v
and it gave the correct result, without segfault.