When should I allocate a bunch? (C ++)

I really don't understand when I should allocate memory on the heap and when I should allocate on the stack. All I really know is that the allocation on the stack is faster, but since the stack size is smaller, I should not use it to allocate large data structures; What else should I consider when deciding on memory allocation? Edit: where should I highlight instance variables?

+3
source share
4 answers
  • Highlight a stack for most objects. Lifetime == scope.
  • If you need to manually control the lifetime of an object, select it on the heap.
  • , .
  • ( ) RAII 2 3, , , - , std:: shared_ptr/:: shared_ptr.
+4

, .

+2

, , . ,

  • (, int double MyClass temp1;
  • (, , char local_buf[100]; MyDecimal numbers[10];

( " " ), , , , , (, do char large_buf[32*1024*1024];)

, , , , ( , , ), , )

:

{
char locBuf[100]; // 100 character buffer on the stack
std::string s;    // the object s will live on the stack
myReadLine(locBuf, 100); // copies 100 input bytes to the buffer on the stack
s = myReadLine2();
  // at this point, s, the object, is living on the stack - however 
  // inside s there is a pointer to some heap allocated storage where it
  // saved the return data from myReadLine2().
}
// <- here locBuf and s go out-of-scope, which automatically "frees" all
//  memory they used. In the case of locBuf it is a noop and in the case of
//  s the dtor of s will be called which in turn will release (via delete)
//  the internal buffer s used.

, , : ( new), -. (std::string, std::vector ..)

0

, .

int numberOfInts;
cout << "How many integers would you like to store?: ";
cin >> numberOfInts;
int *heapArray = new int[numberOfInts];

ints size numberOfInts. , , , .

0

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


All Articles