Using New and Delete to manage memory directly (new header)

Using new to Dynamically allocate and initialize objects (new)

1.Initialization with parentheses and curly braces.

int *pi = new int(1024); 
string *ps = new string(10, '9');
vector<int> *pv = new vector<int>{0,1,2,3,4,5,6,7,8,9};

2.Difference default initialization between int and string.

  • pi points to a dynamically allocated, unamed, uninitialized int.
string *ps = new string;  // default initialized to the empty string.
int *pi = new int;  // default initialized; *pi is undefine.

3.We can use auto only with a single initializer inside parentheses.

auto p1 = new auto(obj);  // p points to an object of the type of obj.
                          // that object is initialized from obj.
auto p2 = new auto{a, b, c};  // error:must use parentheses for the initializer.

4.use new to allocate const objects.

  • A dynamically allocated const object must be initialized.

5.If new is unable to allocate the requested storage:

  • It throws an exception of type bad_alloc.
  • Using new (nothrow) to avod throwing an exception, and returns a null ptr.
int *p2 = new (nothrow) int;  // if allocation fails, new returns a null ptr.

Freeing dynamic memory with delete

1.A delete expression takes a pointer to the object we want to free:

  • must point to a dynamically allocated obj or be null.(otherwise undefined)

2.Although the value of a const obj cannot be modified, the obj itself can be destroyed.

const int *pi = new const int(1024);
delete pi;  // ok: delete a const obj.

3.Set p to nullptr to provide only limited protections.

  • Avoiding dereference dangling ptr to make system crash.
int *p(new int(42));  // p points to dynamic memory.
auto q = p;  // p and q point to the same memory.
delete p;  // invalidates both p and q.
p = nullptr;  // indicates that p is no longer bound to an obj.
posted @ 2022-02-03 15:11  Dy2MoRaw  阅读(59)  评论(0)    收藏  举报