An 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 need an array of classes like this, will I have to use a pointer to a pointer? (and use 'new' on each element of the array) EG: temp **t;
  • if I want to make an array of 100 ptr into ptr, I have todo temp **t = new temp[100][1]; - is there the best way to do this without 4 square brackets?
+3
source share
3 answers

The code:

t = new temp[100];

Builds an array of 100 temp objects. A safer way to do the same:

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

which frees you from having to call delete [] in the array.

+12
source

Try to avoid new things until you really understand what you are doing.

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

. [] .

temp foo2; t[1] = foo2;

. .

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

void foo2(temp& lt)
{
}

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

-, , std::vector. std::vector , . - C, ++.

: . , .

t = new temp[100];, :

  • ( "" )
  • t .

p[i], *(p + i). :

  • t[0] *(t + 0), *t, , t : .
  • t[1] *(t + 1). t , t + 1 : . , *(t + 1) .

, temp * temp, temp.

, , 6 comp.lang.c FAQ, , , C, ++; , ++ , : std::vector. std::vector , .

+1
source

Source: https://habr.com/ru/post/1733514/


All Articles