【问题标题】:std::map works on Windows 32bit but crashes on 64bitstd::map 在 Windows 32 位上工作,但在 64 位上崩溃
【发布时间】:2012-04-17 08:23:51
【问题描述】:

我有一个包含两个条目的字符串映射: "Chicago"--> ChicagoObj"NewYork"-->NewYorkObj,其中 ChicagoObjNewYorkObj 是指向 MyClass 对象的指针。

以下代码在 32 位编译和运行良好,它在 64 位编译,但在打印出芝加哥条目后总是在 64 位崩溃。任何帮助表示赞赏!

typedef std::map<std::string, MyClass*> MyStringMap;
MyStringMap my_map;

std::string key1="Chicago";
MyClass *ChicagoObj = new MyClass;
my_map[key1] = ChicagoObj;

std::string key2="NewYork";
MyClass *NewYorkObj = new MyClass;
my_map[key2] = NewYorkObj ;

MyStringMap::iterator iObjMap = my_map.begin();

while (iObjMap != my_map.end())
{
    std::string key = iObjMap->first;

    std::cout<<"name of the key in the map: " << key <<std::endl;
    iObjMap++;
}

【问题讨论】:

  • 我看到“string”和“std::string”的混合使用,我认为是错字,否则“string”可能根本不是“std::string”。
  • 你不应该使用 C 风格的转换和像 std::string 这样的对象类型,即使在这种情况下它看起来无害。
  • 首先,去掉演员表——他们不应该被需要,而且可能掩盖了问题。其次,去掉printf,它不是类型安全的。您还没有显示MyClassmy_map 的定义,这在这里可能很重要。
  • 欢迎来到 StackOverflow!您的测试用例至少丢失了int main()。请创建一个 shortcomplete 测试用例来演示您的问题。请参阅sscce.org 了解更多信息。
  • @Chad - “代码......确实编译并运行”。这就是为什么我们应该向他询问运行的代码的更多原因。他发布了有效的代码;大概他还没有发布失败的代码。

标签: c++ string 64-bit 32-bit


【解决方案1】:

您确定您已编译了最新的代码并且没有运行具有先前错误的程序吗?我已经在 Windows 7 64 上的 Visual Studio 2010 中编译了您的代码,没有任何问题。

您的代码中存在编译错误,std::out 应该是 std::cout。但除此之外,/Wall 甚至没有发出警告。

【讨论】:

  • "甚至没有来自 /Wall 的警告。"那不可能是真的。标准库头文件(如&lt;map&gt;)不能用/Wall 干净地编译。你是说/W4吗?
【解决方案2】:

由于您显然不会发布一段完整的、可编译的代码来演示该问题,因此这里有一个简短的演示,说明它是如何工作的:

#include <map>
#include <iostream>
#include <string>
#include <iterator>

class City {
    unsigned int population;
    // probably more stuff here, but this should be enough for now.
public:
    City(int pop=0) : population(pop) {}

    friend std::ostream &operator<<(std::ostream &os, City const &c) {
        return os << c.population;
    }

};


std::ostream &operator<<(std::ostream &os, 
                         std::pair<std::string, City> const &d) 
{
    return os << d.first << ": " << d.second;
}

int main() {
    std::map<std::string, City> cities;
    typedef std::pair<std::string, City> ct;

    cities["Chicago"] = City(3456789);
    cities["New York"] = City(8765432);

    std::copy(cities.begin(), cities.end(), 
        std::ostream_iterator<ct>(std::cout, "\n"));

    return 0;
}

我已经在 64 位 Windows 上编译并测试了它,它似乎工作得很好。看起来(至少在我看来)map 在 64 位 Windows 上运行没有问题。很难猜出你所做的究竟是什么造成了破坏,但扩展工作代码以做你想做的事情可能比找出不起作用的代码中的什么问题更容易。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-17
    • 1970-01-01
    • 1970-01-01
    • 2011-03-04
    • 2015-11-07
    • 2013-05-01
    • 1970-01-01
    • 2015-08-18
    相关资源
    最近更新 更多