Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/133.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 删除导致意外崩溃_C++_Constructor_Crash_Destructor - Fatal编程技术网

C++ 删除导致意外崩溃

C++ 删除导致意外崩溃,c++,constructor,crash,destructor,C++,Constructor,Crash,Destructor,这是我写的一个简单的程序: 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; //de

这是我写的一个简单的程序:

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;
}
使用名称空间std;
int main(){
string*word=新字符串[1];//创建字符串对象
*word=“blabla”//为该对象指定一个字符串
库特
那么我如何创建一个对象数组呢?我是否错误地认为
string*word=newstring[1]
只创建一个对象

有点

您正在创建一个包含1个对象的数组

您正在创建一个对象。没错。您仍在创建一个数组

因此,您需要使用
delete[]
表单

delete [] word;


您可以像这样删除数组
delete[]word
。创建的对象数量无关紧要。如果使用
new[]
则必须使用
delete[]
。如果你不是在玩指针,我建议你改用
std::vector
delete ar
工作只是巧合?@HichigayaHachiman,这是正确的理解。你需要使用
delete[]ar;
delete [] ar;