c++ - 赋值运算符重载 : Error Handling scenario

标签 c++ string

回答问题前请引用以下程序。在评论中解释了代码。

所以我的问题是赋值运算符重载如何处理 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

然后考虑operator new始终返回非空指针(除非您还实现了非标准的自定义 new 运算符),如果分配数据失败,则会抛出 std::bad_alloc 异常.如果你想处理分配失败的情况,你需要添加一个 try-catch block

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

关于c++ - 赋值运算符重载 : Error Handling scenario,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32734673/

相关文章:

php - 如何检查字符串是 int,但不是 double 等?

c++ - gcc 对 `std::random_device` 的实现是否正确?

Java:用方法结果替换 RegEx

python - 如何在 python 3.4 中检查数组中元素的字符串

带有 unsigned int 参数的 C++ 函数在用负数调用它时得到奇怪的结果

java - 在java中将大量字符串数据写入文件,优化选项

c++ - std::string 内存管理

c++ - 查找最长公共(public)子串

c++ - 在整数数组上使用 stoul 时 std::string 的输出错误

c++ - 如何获得可调用类型的签名?