Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Consider the following code:

class myarray
{
    int i;

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

}

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
245 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

myarray stackArray[100]; // 100 objects

And on the heap? (or "freestore"):

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

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 };

Or with a vector:

// 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)
    {}
};

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...