C ++ | dynamic memory

content

  1. Dynamic Memory and smart pointers
  2. Dynamic Array
  3. Use library: text query program
  4. to sum up

0. Summary

Object (dynamically allocated objects) dynamic allocation of life (lifetime) independent of its place was created, they have to be clear there will be released (free).

To make use of dynamically allocated objects safer, library defines two smart pointers (smart pointer) types to manage dynamically allocated objects. Smart pointers to ensure that automatically releases the object to which it points at the right time.

  • static memory and stack memory
    • static memory:
      • for local static objects
      • for class static data members
      • for variables defined outside any function
    • stack memory
      • for nonstatic objects defined inside functions
    • automatically created and destroyed by the compiler; static objects are allocated before they are used and are destroyed when the program ends.
  • heap memory (free store)
    • for dynamically allocated objects, that is, objects that the program allocate at run time.
    • must explicitly destroy

1. Dynamic Memory and smart pointers

operators:

  • new new : memory allocation, initialization object returns a pointer to that object;
  • the Delete : to destroy the object, freeing memory.

Dynamic Memory difficulties:

  • Memory leaks (memory leak): Forget release memory
  • Illegal pointer: points to be freed memory

Smart pointers (C ++ 11): like an ordinary pointer as to use and has an important feature that can automatically delete the object to which it points.

  • shared_ptr: allows multiple pointers to refer to the same object
    • weak_ptr: a weak reference to an object managed by a shared_ptr
  • unique_ptr: owns the object to which it points

1.1 shared_ptr class

Like vector, as it is also the smart pointer template. Therefore, when you create a smart pointer, the need to provide additional information, that is, it points to an object of type.

shared_prt<string> p1; // shared_ptr可以指向一个字符串

Using smart pointers similar way as with a pointer. To quote (dereference) a smart pointer will return the object to which it points.

// 如果p1不是空指针,检查其指向的空字符串 if (p1 && p1->empty()) *p1 = "hi"; // 去引用并赋新值给字符串

make_shared function

The use of dynamic memory allocation and safest way is to call a library function, " make_shared."

#include <memory> // for the use of 'make_shared'

// shared_ptr that points to an int with value 42
shared_ptr<int> p3 = make_shared<int>(42);
// p4 points to a string with value 999999999
shared_ptr<string> p4 = make_shared<string>(10, '9');
// p5 points to an int that is value initialized to 0
shared_ptr<int> p5 = make_shared<int>();

2. Dynamic Array

3. Use the library: text query program

4. Summary

reference

  • 《C++ Primer, Fifth Edition》, Stanley B. Lippman

Guess you like

Origin www.cnblogs.com/casperwin/p/12563628.html