抛出异常:读取访问冲突。 _Pnext 是 0x148F854。 (C++ 析构函数错误)

Exception thrown: read access violation. _Pnext was 0x148F854. (C++ Destructor Error)

case 4: //  ----------------------------------------    Delete Customer
                cout << "Enter your Customer ID:" << endl;
                cin >> exist_id;
                for (int i = 0; i <= cnum; i++) {
                    if (c[i].C_ID() == exist_id) {
                        cc = 't'; // check to set customer found.

                        c[i].~customer(); // error occurs here

                        c[i].id(NULL);
                        cout << "Deletion Successful" << endl << endl;
                        break;
                    }
                };

                if (cont(cc) == false) {
                    cout << "CUSTOMER NOT FOUND" << endl << endl;
                }
                cc = 'f';
                //system("CLS");
                break;

在上述情况下,我抛出了 异常:读取访问冲突。 _Pnext 是 0x148F854。错误。

代码 运行 完美于 2-3-2020。但是今天从数组中删除客户时出现此错误。

Visual Studio Error alert

C++ 中的析构函数在对象 dies/destroys 首先处理不需要的已分配内存时默认调用,不应在其他任何地方调用它。

对于您的情况,我认为最佳做法是在 customer class 中创建一个成员函数 delete_customer,在析构函数中具有确切的代码。

或者,为了不重复代码两次,您可以在对象死亡时调用析构函数中的delete_customer函数。

希望这能解决您的问题!