赋值操作符重载:错误处理场景
Assignment operator overload : Error Handling scenario
回答问题前请参考以下程序。在注释中解释代码。
所以我的问题是在赋值操作符重载中如何处理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;
首先在临时变量中分配内存,如果成功,则只删除旧值。
相关文章:
- 使用返回对象的函数处理错误
- C++:处理错误,看不懂我的错误
- 如何处理错误"E1696命令行错误:无法在Visual Studio 2017中打开元数据文件"mscorlib.dll"?
- C++ 异常处理错误输出
- 信号处理错误
- 文件处理I/O C 错误
- 文件处理 - 错误:与 while 循环 (C++) 中的"运算符>>"不匹配(代码::块)
- SDL的事件处理错误
- HMODULE在重建导入地址表IAT时处理错误
- C++ 中的文件处理错误 - 调用"std::basic_fstream<char, std::char_traits<char> >::open(const char[8],
- 在处理线程时,处理错误的正确方法是什么
- 处理C++错误
- 异常处理C++错误
- CUDA图像处理错误
- 文件处理错误
- 代码::阻止资源预处理错误
- 使用模板创建类的新实例,不知道如何处理错误
- Qt 与 opencv 异常处理错误
- 提升 MSM 中的错误处理错误
- 如何处理错误“vtkTrivialProducer :此数据对象不包含请求的范围”