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

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

问题描述

考虑以下code:

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 ::矢量

#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 ++并没有真正有一个堆或堆/的FreeStore。我们所拥有的是自动存储和动态存储的持续时间。在实践中,这赞同堆栈分配和堆分配。


† 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.

††如果你想从堆栈动态分配,你需要定义一个最大尺寸(堆栈存储事先已知的),然后给矢量新分配器所以它使用堆栈来代替。

†† 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天全站免登陆