-3
class String
{
private:
char *s;
int size;
public:
String(const char *str = NULL); // constructor
~String() { delete [] s; }// destructor
//String(const String&); // copy constructor --> i get double free error while running without this
void print() { cout << s << endl; } // Function to print string
void change(const char *); // Function to change
};
String::String(const char *str)
{
size = strlen(str);
s = new char[size+1];
strcpy(s, str);
}
void String::change(const char *str)
{
delete [] s;
size = strlen(str);
s = new char[size+1];
strcpy(s, str);
}
/*String::String(const String& old_str)
{
size = old_str.size;
s = new char[size+1];
strcpy(s, old_str.s);
}*/
int main()
{
String str1("Hello");
String str2 = str1;
str1.print(); // printed
str2.print();
str2.change("Helloworld");
str1.print(); // not printed
str2.print();// printed
return 0;
}
http://ideone.com/xJtoTf獲得雙重釋放錯誤時不使用拷貝構造函數
我得到一個雙錯誤並沒有被打印的str1
打印第二次(見上面的代碼中的註釋)...
是因爲當我在這裏不使用複製構造函數時,而是使用被調用的默認拷貝構造函數,並且str2
和str1
都指向相同的位置?
http://en.cppreference.com/w/cpp/language/rule_of_three –
@HansPassant謝謝.. – 0xdeadbeef