c++ - 在 C++ 中分配内存而不初始化它

标签 c++ memory new-operator

我正在熟悉 C++,但在内存管理方面遇到了问题。在 C 语言中,每当我想为任意数量的元素保留内存时,无论类型如何,我都只需调用 malloc() 然后手动初始化(通过循环)到我想要的任何值通缉。使用 C++ 的 new,一切都会自动初始化。

问题是,我有一个 BattlePoint 类,它有点像这样:

class BattlePoint {
public:
    BattlePoint(int x, int y) : x(x), y(y) { };
    bool operator==(const BattlePoint &right);
    virtual ~BattlePoint();

private:
    int x, y;
};

如您所见,它通过初始化程序获取一些 x 和 y 值,然后从中设置自己的 x 和 y。问题是,这个函数将从一个分配数组的函数中调用:

BattleShip::BattleShip(BattlePoint start, enum shipTypeSize size, enum shipOrientation orientation) : size(size), orientation(orientation) {
    points = new BattlePoint[size]; // Here be doubts.
}

因此,我需要我的 BattleShip 点数来保存一组 BattlePoints,每个点数都有不同的初始化值(例如 0,1;0,2;0,3 等)。

问题是:我如何分配未初始化的内存?

朱利安

P.S.:我还没有对 new 的工作方式进行任何测试,我只是简单地阅读了 Wikipedia's article on it其中说:

In the C++ programming language, as well as in many C++-based languages, new is a language construct that dynamically allocates memory on the heap and initialises the memory using the constructor. Except for a form called the "placement new", new attempts to allocate enough memory on the heap for the new data. If successful, it initialises the memory and returns the address to the newly allocated and initialised memory. However if new cannot allocate memory on the heap it will throw an exception of type std::bad_alloc. This removes the need to explicitly check the result of an allocation. A call to delete, which calls the destructor and returns the memory allocated by new back to the heap, must be made for every call to new to avoid a memory leak.

placement new 应该是解决方案,但它没有提到如何去做。

附言2:我知道这可以通过 stdlib 的 vector 类来完成,但我是故意避免的。

最佳答案

您需要使用 std::vector。在这种情况下,您可以push_back任何您想要的,例如

std::vector<BattlePoint> x;
x.push_back(BattlePoint(1, 2));

如果您曾经发现自己在使用new[]deletedelete[],请重构您的程序立即删除此类。它们几乎在所有可以想象的方面都非常不安全。相反,使用资源管理类,例如 std::unique_ptrstd::vectorstd::shared_ptr

常规 new 可以在某些涉及 unique_ptr 的情况下很有用,但要避免使用它。此外,安置新的通常是不值得的。当然,如果您正在编写资源管理类,那么您可能必须将它们用作底层原语,但这种情况很少见。

编辑:我的错误,我没有看到你问题的最后一行。解决它:

P.S. 2: I know this can be done through stdlib's vector class, but I'm avoiding it on purpose.

如果您有一些针对标准库的事件,请使用您自己的 vector 替代品。但是不要没有 vector 类。所有符合标准的编译器必须提供它是有原因的。

关于c++ - 在 C++ 中分配内存而不初始化它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8632346/

相关文章:

c++ - 下标值不是数组(错误)

c++ - Qt 的 std::unordered_set 模拟/对应

c++ - 这两个陈述有什么不同

c++ - Qwt内存泄漏

c++ - 为什么new第一次会多分配1040字节?

c++ - 我需要自定义 SDL 事件。我应该修改 SDL 还是以其他方式获取输入?

java - 高效的图像调整大小

c++ - 通过类函数在堆上创建对象

c++ - new 和 new[1] 有什么区别?

winapi - VirtualAlloc 和 HeapAlloc 有什么区别?