在我搜索了如何验证指针是否在C ++中被删除之后,我发现没有特定的方法,一些非常难看的解决方法或智能指针(我首先要了解正常指针是如何工作的)。我的问题是当我尝试使用try / catch来显示已删除指针的值时C ++崩溃的原因?它不应该处理崩溃并只打印异常??
void main()
{
int *a = new int[5];
for (int i = 0; i < 5; i++)
{
*(a + i) = i;
}
for (int i = 0; i < 5; i++)
{
if (*(a + i) != NULL) // useless verify, cuz if it would be NULL, it
//would crash imediately
{
cout << (a + i) << ", " << *(a + i) << endl;
}
}
delete a;
cout << a << ", ";// << *a << endl;
for (int i = 0; i < 5; i++)
{
try{
cout << (a + i) << ", " << *(a + i) << endl;
}
catch (int e)
{
cout << "Error: " << e << endl;
}
}
cin.get();
}
答案 0 :(得分:4)
try{
cout << (a + i) << ", " << *(a + i) << endl;
}
catch (int e)
{
cout << "Error: " << e << endl;
}
只有在抛出异常时才能捕获异常。访问释放的内存是Undefined Beahvior并且不会抛出异常,因此无需捕获。
答案 1 :(得分:0)
首先对于数组删除,语法为Sub Import_text()
Dim xWb As Workbook
Dim xToBook As Workbook
Dim xStrPath As String
Dim xFileDialog As FileDialog
Dim xFile As String
Dim xFiles As New Collection
Dim I As Long
Set xFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
xFileDialog.AllowMultiSelect = True
xFileDialog.Title = "Select a folder"
If xFileDialog.Show = -1 Then
xStrPath = xFileDialog.SelectedItems(1)
End If
If xStrPath = "" Then Exit Sub
If Right(xStrPath, 1) <> "\" Then xStrPath = xStrPath & "\"
'xFile = Dir(xStrPath)
xFile = Dir(xStrPath & "*.txt") 'this is the original version that you can amend according to file extension
If xFile = "" Then
MsgBox "No files found", vbInformation, "Summary"
Exit Sub
End If
Do While xFile <> ""
xFiles.Add xFile, xFile
xFile = Dir()
Loop
Set xToBook = ThisWorkbook
If xFiles.Count > 0 Then
For I = 1 To xFiles.Count
Set xWb = Workbooks.Open(xStrPath & xFiles.Item(I))
xWb.Worksheets(1).Copy after:=xToBook.Sheets(xToBook.Sheets.Count)
On Error Resume Next
ActiveSheet.Name = xWb.Name
On Error GoTo 0
xWb.Close False
Next
End If
End Sub
其次,try catch块不用于处理损坏的地址,不幸的是C ++中的内存访问冲突没有异常处理。
答案 2 :(得分:-1)
在这种情况下,没有异常抛出,只是未定义的行为。例外情况是明确捕获正在抛出的异常。
另外,使用delete [] a;
代替delete a;
删除数组。
此外,当我们delete
内存时,内存实际上并未实现已删除,但从现在开始可以自由覆盖。
cout
打印的内容并未说明指针是否为deleted
。