赋值操作符重载:错误处理场景

Assignment operator overload : Error Handling scenario

本文关键字:处理 错误 重载 赋值操作符      更新时间:2023-10-16

回答问题前请参考以下程序。在注释中解释代码。

所以我的问题是在赋值操作符重载中如何处理new()未能分配内存的情况。

例如:Obj1持有字符串"GeeksQuiz"。将Obj2分配给Obj1。在赋值过程中(在赋值操作符重载函数中),我们首先释放Obj1,然后用Obj2的值重新创建Obj1。因此,在new无法分配内存的情况下,如何保留旧的Obj1值?因为我们在函数开始时释放了Obj1值。

当赋值操作失败时,我想要的是Obj1的旧值。

请帮我一下。我想要完美的代码,没有任何内存泄漏覆盖所有场景。提前感谢

#include<iostream>
#include<cstring>
using namespace std;
class String
{
private:
    char *string_data;
    int size;
public:
    String(const char *str = NULL); // constructor
    ~String() { delete [] string_data;  }// destructor
    void print() { cout << string_data << endl; } // Function to print string
    String& operator = (const String &); // assignment operator overload
};
String::String(const char *str)  // Constructor
{
    size = strlen(str);
    string_data = new char[size+1];
    if (string_data != NULL)
        strcpy(string_data, str);
    else
        cout<<"compiler failed to allocate new memory";
}
String& String::operator = (const String &str) // assignment operator overload
{
    if(this != &str) 
    {
        delete [] string_data; // Deleting old data and assigning new data below
        size = str.size;
        string_data = new char[size+1];
        if(string_data != NULL) // This condition is for cheking new memory is success 
            strcpy(string_data, str.string_data);
        else
            cout<<"compiler failed to allocate new memory"; // My quetsion comes in this scenario...
    }
    return *this;
}
int main()
{
    String Obj1("GeeksQuiz");
    String Obj2("stackoverflow");
    Obj1.print(); // Printing Before assigment
    Obj2.print();
    Obj1 = Obj2;  // Assignment is done. 
    Obj1.print(); // Printing After assigment
    Obj2.print();
    return 0;
}

首先,实现一个健壮的字符串是困难的,除非你想为了学习目的而这样做,总是使用std::string

然后考虑到操作符new总是返回非空指针(除非你也实现了一个非标准的自定义new操作符),相反,如果分配数据失败,它会抛出std::bad_alloc异常。如果你想处理分配失败的情况,你需要添加一个try-catch块

char *data = NULL;
try {
  data = new char[str.size + 1];
} catch (std::bad_alloc &e) {
  std::cout << "Allocation failed: " << e.what() << std::endl;
  throw; // <- You probably want to rethrow the exception.
}
strcpy(data, str.string_data);
delete [] string_data;
string_data = data;
size = str.size;
重要的部分是在抛出异常时使类保持一致状态,这就是为什么必须首先分配新数据,然后如果成功,则删除旧数据。然而,bad_alloc异常很少在类级别处理,通常您让异常被抛出(这就是为什么我在代码示例中重新抛出),并让客户端代码处理它。

如果你真的想让你的代码是异常证明,我会建议使用智能指针,并且已经说过,在这种情况下使用std::string

临时变量或虚拟变量。

分配新内存,将指针赋给临时变量。如果操作成功,则释放旧内存并重新分配该指针变量。


Pseudo-ish代码:

char *temp = new char[new_size];
std::copy(new_data, new_data + new_size, temp);
delete [] old_data;
old_data = temp;
old_size = new_size;

首先在临时变量中分配内存,如果成功,则只删除旧值。