如何在 C++ 中释放 class 实例数组?

How to deallocate array of class instances in C++?

我在做一个小游戏,我把地图存储在一个数组中,我想不用告诉你的原因我的地图不只是一个char数组,我做了一个class:

enum Marks { N, Ex3, Ex2, Ex1, Pl, En, Pb, Eb};

class MC /*Map Component*/{
public:
    Marks Marked = Marks::N;
    char ch = '[=11=]';
};

我的数组是这个 class 实例的数组,但是 bcs,根据 Visual Studio,我的映射对于堆栈来说太大了,我进行了堆分配,MC* map = new MC[1050]; // 15 * 70

一切正常,直到玩家死亡,游戏结束,删除地图的时间到了,delete[] map抛出Invalid address specified to RtlValidateHeap([some hexadecimal number, an address probably], [some hexadecimal number, an address probably])

我知道我可以使用 vectors,但我只是不想,我想了解更多关于内存管理的知识,更熟悉指针等


编辑:Visual Studio 还会打开一个名为 delete_scalar.cpp 的文件。 该文件的代码:

//
// delete_scalar.cpp
//
//      Copyright (c) Microsoft Corporation. All rights reserved.
//
// Defines the scalar operator delete.
//
#include <crtdbg.h>
#include <malloc.h>
#include <vcruntime_new.h>
#include <vcstartup_internal.h>

////////////////////////////////////////////////////////////////
// delete() Fallback Ordering
//
// +-------------+
// |delete_scalar<----+-----------------------+
// +--^----------+    |                       |
//    |               |                       |
// +--+---------+  +--+---------------+  +----+----------------+
// |delete_array|  |delete_scalar_size|  |delete_scalar_nothrow|
// +--^----^----+  +------------------+  +---------------------+
//    |    |
//    |    +-------------------+
//    |                        |
// +--+--------------+  +------+-------------+
// |delete_array_size|  |delete_array_nothrow|
// +-----------------+  +--------------------+

_CRT_SECURITYCRITICAL_ATTRIBUTE
void __CRTDECL operator delete(void* const block) noexcept
{
    #ifdef _DEBUG
    _free_dbg(block, _UNKNOWN_BLOCK);
    #else
    free(block);
    #endif
}

经过一些测试,我发现程序在 delete[] 之后崩溃,我的意思是:

//
// code that runs the game
//
std::cout << endl << "Before delete";
_getch();
delete[] map;
std::cout << endl << "After delete";
_getch();
return; //function is void and is not main()

输出:

Before delete
//me pressing something
After delete
//me pressing something
//program crashes

道歉:bcs Visual Studio 打开了 delete_scalar.cpp 我以为 delete[] 导致程序崩溃,现在我只是不知道,我很困惑。

好吧,非常抱歉,原来我是个彻头彻尾的白痴,我的愚蠢是无止境的。我这样说的原因:随着游戏的运行,某些类型的对象一直被创建、删除和重新创建,而我将它们分配到堆中的 bcs,但我忘了让我的程序 delete 它们在如果他们在玩家死亡的那一刻“还活着”,我简直不敢相信我是多么的白痴才花 3 天时间做这样的事情。

感谢所有试图解决我的问题的人,即使他们没有所需的信息,我也不知道到底需要什么信息所以...是的,我很抱歉