删除导致意外崩溃
Delete causes unexpected crash
这是我写的一个简单的程序:
using namespace std;
int main() {
string *word = new string[1]; //create a string object
*word = "blablabla"; //assign a string to that object
cout << "String: " << *word << endl;
delete word; //delete object? Causes unexected crash
int *ar = new int [10]; //create array of 10 blocks
ar[3] = 4; //assign a value to bl-3
cout << ar[3] << endl;
delete ar; //delete object, works
return 0;
}
现在据我了解,delete
与 new
(如删除我创建的一个对象)和 delete[]
与 new[]
(删除并创建一个对象数组)。问题是前者 delete
导致我的程序崩溃,而后者工作正常。但是,delete[] word
有效。
那么我如何创建对象数组?我是不是误以为 string *word = new string[1]
只创建了一个对象?
So how am I creating an array of objects? Am I mistaken in thinking that string *word = new string[1]
creates just one object?
有点。
您正在创建一个包含 1 个对象的数组。
您正在创建一个对象。这是真的。您仍在创建数组。
因此,您需要使用 delete []
形式。
delete [] word;
和
delete [] ar;
这是我写的一个简单的程序:
using namespace std;
int main() {
string *word = new string[1]; //create a string object
*word = "blablabla"; //assign a string to that object
cout << "String: " << *word << endl;
delete word; //delete object? Causes unexected crash
int *ar = new int [10]; //create array of 10 blocks
ar[3] = 4; //assign a value to bl-3
cout << ar[3] << endl;
delete ar; //delete object, works
return 0;
}
现在据我了解,delete
与 new
(如删除我创建的一个对象)和 delete[]
与 new[]
(删除并创建一个对象数组)。问题是前者 delete
导致我的程序崩溃,而后者工作正常。但是,delete[] word
有效。
那么我如何创建对象数组?我是不是误以为 string *word = new string[1]
只创建了一个对象?
So how am I creating an array of objects? Am I mistaken in thinking that
string *word = new string[1]
creates just one object?
有点。
您正在创建一个包含 1 个对象的数组。
您正在创建一个对象。这是真的。您仍在创建数组。
因此,您需要使用 delete []
形式。
delete [] word;
和
delete [] ar;