C + + Primer Dynamic array of notes in the 12th chapter

Source: Internet
Author: User

New and array

In order for new to assign an array of objects, you must follow the type name followed by []. The number of allocations specified therein;

int New int [Get_size ()]; // [] must be an integral type, but not necessarily a constant;  int arrt[]; int New ARRT; // assigns an array of 24 int, p points to the first int;

Initialization, c++11: Available curly braces {};

It is legal to allocate an empty array dynamically;

To release a dynamic array:

Delete p; Delete []  PA;

Smart pointers vs. dynamic arrays:

The standard library provides a unique_ptr version of an array that can manage new allocations

You must add an empty [] after the type;

// Up points to an array containing 10 uninitialized integers; unique_ptr<int[]> up (newint  [ten]); Up.release ();     // Automatic delete[], destroying its pointer;

Note: The up pointer is an int array, not an int, and the point or arrow member operator cannot be used;

However, you can use the subscript operator to access the elements in the array;

 for (size_t i =0; i!=; + +i) {        = i;}

SHARED_PTR does not support managing dynamic arrays

SHARED_PTR does not define subscript operators, and the smart pointer type does not support pointer arithmetic operations;

If you use it, you must define your own delete;

shared_ptr<int> SP (  newint[ten], [] (intDelete  []p;} ); Sp.reset (); // use a custom lambda to release the array, which uses delete[];

C + + Primer Dynamic array of notes in the 12th chapter

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.