赋值运算符在 xcode 4 中崩溃,在MSVS2010中运行良好

Assignment operator crash in xcode 4, runs fine in MSVS2010

本文关键字:运行 MSVS2010 崩溃 xcode 赋值运算符      更新时间:2023-10-16

我正在使用Visual Studio 2010进行C++项目,一切都很好,但是当我尝试使用xcode 4运行我的程序时,它引发了Bas_Access异常。我认为这是因为内存泄漏,但我不确定如何解决问题。我有以下功能:

// Search is my class with x and y as members and here's is a constructor
// that I cretae in my Search.cpp class
Search& Search::operator=( const Search& search )
{
    if(this != &search)
   {
      x = search.x;
      y = search.y;
   }
   return *this;
}

以下是我的函数的调用方式:

Search searchStart(0,0);
//I created my tempSearch and initialized it with the start Search element
Search tempSearch(searchStart);
//bestSolution is a function that calculates the best neighbour node around the searchStart node, it returns a Search element. And stores it in a list in storage.
Search * tempCurrent=searchStart.bestSolution(&storage);
//Here I call my function
tempSearch=*tempCurrent;    

只是从现有元素创建一个新的搜索元素,但它给了我例外

x=search.x;

它与Visual Studio完美配合。

编辑:我刚刚添加了调用我的函数的代码。请原谅我无法提供完整的代码,因为它真的很长。

编辑:这是我最好的解决方案函数:

Search * searchNode::Search::bestSolution(Storage *storage )
{
        //listResult is a type defined as std::list<Search *> listResult.
    listResult::iterator it, it1;
    listResult tempList;
    //I've initialized the result element at (0,0) because it was creating problems
    // if uninitialized
        Search *result=new Search(0,0);
    //openList is a simple list of Search elements
    if(!storage->openList.empty()){
    for(it=storage->openList.begin();it!=storage->openList.end();it++)
    {
        tempList.push_back((*it));
    }
    tempList.reverse();
    it1=tempList.begin();
    // getDistanceCost is a function that calculates the heuristic distance 
    // between two points and works fine
    int fCost=(*it1)->getDistanceCost();    
    for(it1=storage->openList.begin();it1!=storage->openList.end();it1++)
    {
        if((*it1)->getDistanceCost()<=fCost){
        fCost=(*it1)->getDistanceCost();
        result=(*it1);
    }
    }
    }
    return result;
    }

我的猜测是bestSolution返回指向堆栈上分配的对象的指针。现在,当您尝试tempSearch=*tempCurrent时,您正在尝试将值复制到此无效指针中,这会导致未定义的行为。

编辑

查看 bestSolution 方法的实现,我假设listResult包含Search*作为其节点,就像您正在执行result=(*it1);一样。看起来列表具有指针的Search对象在插入列表被删除了。因此,列表中的内容是一个 invaid 指针。如果您尝试将任何内容复制到此无效指针所指向的内存中,则程序的行为将不可预测。

鉴于您提供的信息,可以肯定问题出在

Search * tempCurrent=searchStart.bestSolution(&storage);

它必须返回一些无效的指针(可能是NULL(。

然后,这个无效的指针作为search参数(更准确地说是&search(传递给你的Search::operator=,然后它试图访问这个无效指针(search.xsearch.y(的x(以及后来的y(成员。