在堆栈和堆上创建对象数组 [英] Creating array of objects on the stack and heap

查看:34
本文介绍了在堆栈和堆上创建对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

class myarray
{
    int i;

    public:
            myarray(int a) : i(a){ }

}

如何在栈上创建myarray的对象数组,如何在堆上创建对象数组?

How can you create an array of objects of myarray on the stack and how can you create an array of objects on the heap?

推荐答案

您可以通过以下方式在堆栈上创建对象数组:

You can create an array of objects on the stack via:

myarray stackArray[100]; // 100 objects

在堆上(或freestore"):

And on the heap (or "freestore"):

myarray* heapArray = new myarray[100];
delete [] heapArray; // when you're done

但最好不要自己管理内存.相反,使用 std::vector:

But it's best not manage memory yourself. Instead, use a std::vector:

#include <vector>
std::vector<myarray> bestArray(100);

向量是一个动态数组,它(默认情况下)从堆中分配元素.††

A vector is a dynamic array, which (by default) allocates elements from the heap.††

因为您的类没有默认构造函数,所以要在堆栈上创建它,您需要让编译器知道要传递给构造函数的内容:

Because your class has no default constructor, to create it on the stack you need to let the compiler know what to pass into the constructor:

myarray stackArray[3] = { 1, 2, 3 };

或者使用向量:

// C++11:
std::vector<myarray> bestArray{ 1, 2, 3 };

// C++03:
std::vector<myarray> bestArray;
bestArray.push_back(myarray(1));
bestArray.push_back(myarray(2));
bestArray.push_back(myarray(3));

当然,你总是可以给它一个默认的构造函数:

Of course, you could always give it a default constructor:

class myarray
{
    int i;    
public:
    myarray(int a = 0) :
    i(a)
    {}
};

<小时>

† 对于学究们:C++ 并没有真正的堆栈"或堆"/自由存储".我们拥有的是自动存储"和动态存储"时长.在实践中,这与堆栈分配和堆分配保持一致.


† For the pedants: C++ doesn't really have a "stack" or "heap"/"freestore". What we have is "automatic storage" and "dynamic storage" duration. In practice, this aligns itself with stack allocation and heap allocation.

†† 如果你想从堆栈中动态"分配,你需要定义一个最大大小(堆栈存储提前知道),然后给 vector 一个新的分配器,以便它使用堆栈.

†† If you want "dynamic" allocation from the stack, you'd need to define a max size (stack storage is known ahead of time), and then give vector a new allocator so it uses the stack instead.

这篇关于在堆栈和堆上创建对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆