c++ - 在 C++ 中对字符串使用复制构造函数和/或赋值运算符时发生堆栈溢出

标签 c++ c++11 stack-overflow copy-constructor assignment-operator

我正在尝试在我自己创建的一个简单类上运行插入排序,它具有几个字段(int、float 和 string)以及一个复制构造函数、赋值运算符和“>”运算符。

但是,当我运行下面的代码时出现堆栈溢出。 visual studio 告诉我它来 self 的“学生”类中的 getName() 函数。错误源于我的插入排序函数 arr[i + 1] = arr[i];

有人知道这是为什么吗?我对 C++ 比较陌生,主要来自 Java 背景。

#include <iostream>
#include <vector>
#include <string>
using namespace std;

class Student {
public:
    Student(string nm, int ID, float avg): name(nm), studentID(ID), overallAverage(avg) {}

    Student(const Student& rhs) : name(rhs.getName()), studentID(rhs.getStudentID()), overallAverage(rhs.getOverallAverage()) {}

    // copy and swap idiom
    Student& operator=(const Student& rhs) {
        Student copy = rhs;  // places a copy of rhs into copy using the copy constructor (copy will be cleaned up on return)
        swap(*this, copy); // move copy or rhs into this, this is a pointer to current object, *this dereferences the pointer
        return *this; 
    }
    ~Student() {}

    bool operator>(const Student& rhs) {
        if (rhs.getOverallAverage() > overallAverage)
            return false;
        else return true; 
    }

    string getName()const { return name; }
    int getStudentID()const { return studentID;  }
    float getOverallAverage()const { return overallAverage; }

private:
    string name; 
    int studentID; 
    float overallAverage; 

};

template<typename T> 
vector<T>& insertionSort(vector<T>& arr){
    for (int j = 1; j < arr.size(); j++) {
        T key = arr[j]; 
        int i = j - 1; 
        while (i > -1 && arr[i] > key) {
            arr[i + 1] = arr[i]; 
            i = i - 1; 
        }
        arr[i + 1] = key; 
    }
    return arr; 
}


int main()
{
    vector<Student> students = {Student("russ",0,89),Student("Seb",1,75),Student("julia",2,85),
                                Student("johnny",3,90),Student("Sushma",4,55)}; 

    students = insertionSort(students); 

    for (int i = 0; i < students.size(); i++) {
        cout << students[i].getName() << ", ";
    }
    cout << endl;  
}

我正在使用的 txtbook 中的原始 operator=:

IntCell & operator= ( const IntCell & rhs ) // Copy assignment
{
IntCell copy = rhs;
std::swap( *this, copy );
return *this;
}

最佳答案

无限递归是由std::swap调用Student::operator=引起的,student::operator=调用std::swapstd::swap调用Student::operator=

为了减轻这种情况,编写您自己的 swap 函数,在每个成员上调用 std::swap:

class Student
{
//...
   void swap(Student& left, Student& right)
    {
        std::swap(left.name, right.name);
        std::swap(left.studentID, right.studentID);
        std::swap(left.overallAverage, right.overallAverage);
    }
//...
};

关于c++ - 在 C++ 中对字符串使用复制构造函数和/或赋值运算符时发生堆栈溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59698708/

相关文章:

c++ - 使用指针在 C++ 中显示 char 变量的地址?

c++ - 使用 C++11 编写 Win32 应用程序

c++ - 无论如何我可以让一个模板<typename T>接受多个值吗?

c - 由于重复递归而超出堆栈限制

c++ - free() 导致堆栈溢出

c++ - 在 Arraydeque 中制造异常不会停止执行

c++ - 返回 lambda 表达式的函数

c++ - 不在包含路径中搜索

c++ - 用另一个字符序列替换 C++ std::string 中的字符/字符序列

c++ - 构造函数中神秘的堆栈溢出