請在回答問題前參閱下面的程序。在評論中解釋代碼。分配操作員超載:錯誤處理方案
所以我的問題是在賦值運算符重載如何處理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;
}
先分配,然後如果全部刪除舊數據。 –
您賦值運算符中的「if」路徑不返回任何內容。 – Drax
爲什麼你認爲你可以 - 爲了好玩(或練習?) - 實現一個健壯的字符串類?如果你想用C++編程,學習使用它的標準庫! – Wolf