vendredi 31 août 2018

Can we use conventional pointer arithmetic with std::array?

I want to work out how to use old style pointer arithmetic on pointers to elements of the std::array class. The following code (unsurprisingly perhaps) does not compile:

int main(int argc, char *argv[])
{
    double* data1 = new double[2];
    std::cout << *data1 << " " << (data1 +1)* << std::endl;
    delete data1;
    data1 = NULL;

    double* data2 = new std::array<double, 2>;
    std::cout << data2* << " " << (data2 +1)* << std::endl;
    delete data2;
    data2 = NULL;

    return 0;
}

As an exercise, I want to use all the conventional pointer arithmetic, but instead of pointing at an old style double array, I want it to point to the elements of a std::array. My thinking with this line:

    double* data2 = new std::array<double, 2>;

is to instruct the compiler that data2 is a pointer to the first element of the heap allocated std::array<double,2>.

I have been taught that the double* name = new double[size]; means EXACTLY the following: «Stack allocate memory for a pointer to ONE double and name the pointer name, then heap allocate an array of doubles of size size, then set the pointer to point to the first element of the array.» Since the above code does not compile, I must have been taught something incorrect since the same syntax doesnt work for std::arrays.

This raises a couple of questions:

  1. What is the actual meaning of the statement type* name = new othertype[size];?
  2. How can I achieve what I want using std::array?
  3. Finally, how can I achieve the same using std::unqiue_ptr and std::make_unique?

Aucun commentaire:

Enregistrer un commentaire