开发者

Array of classes. Stack or heap?

class temp;

temp *t;

void foo() { temp foo2; t[1] = foo2; }

int main() { 
    t = new temp[100];
    foo();
    //t[1] is still in memory?
}
  • If i want an array of classes like this, am i going to have to use pointer to pointer? (and use 'new' on each element in the array) E.G: temp **t;
  • if i wan开发者_Go百科t to make an array of 100 ptr to ptr i have todo temp **t = new temp[100][1]; is there a better way to do that without 4 square brackets?


The code:

t = new temp[100];

constructs an array 100 objects of type temp. A safer way to do the same thing is:

std::vector <temp> t(100);

which absolves you of ever having to call delete[] on the array.


Try to avoid the new stuff at all until you exactly know what you are doing.

std::vector<temp> t(100);

will do the job in a perfect manner. You still can access it using [] operator and like in your solution.

temp foo2; t[1] = foo2;

will call the assignment operator of the temp class. use & for passing the variable to a function.

void foo1(std::vector<temp>& lt)
{
}

void foo2(temp& lt)
{
}

foo1(t);
foo2(t[1]);


Firstly, I support the other's suggestions to avoid new and use std::vector instead. std::vector saves many headaches caused by pointers and arrays. Arrays are very much a C solution, not a C++ solution.

To answer your question: you do not need a pointer-to-pointer type here. The reason is that arrays are naturally addressed by pointer.

When you say t = new temp[100]; two things happen:

  • A new array is allocated from the free store (or 'heap')
  • t is set to point to the new array's first element.

When you use the p[i] operator, it is actually syntactic sugar for *(p + i). For example:

  • t[0] is equivalent to *(t + 0) which is just *t, or the element that t points at: the first element of the array.
  • t[1] is equivalent to *(t + 1). Since t is a pointer to the first element of the array, t + 1 is a pointer to the element one place beyond the first: the second element. So *(t + 1) gives you the second element.

Using this system, a temp * pointer can be used to refer to a whole array of temp, instead of just a single temp instance.

If you really want to learn about arrays and pointers, you could do worse than read chapter 6 of the comp.lang.c FAQ. Note, however, that this is a C resource, not a C++ resource; this is because in C++, arrays are generally not used because you have a better feature available: std::vector. I strongly recommend you make learning about std::vector a higher priority than learning about pointers and arrays.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜