zar
zar

Reputation: 12247

difference between array and plain pointer with std::unique_ptr

There is:

std::unique_ptr< double> d( new double[3] );

and

std::unique_ptr< double[]> darr( new double[3] );

At least one of the difference between the two seem to be that the later calls delete[] but both are valid..but how come? I mean how is memory deleted in first case, isn't that undefined behavior deleting array with delete?

Secondly I know darr above has [] operator defined but how to access 2nd and 3rd member of d since there is no [] operator defined.

Why would anyone use the first syntax rather than the 2nd?

Upvotes: 0

Views: 166

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 598134

At least one of the difference between the two seem to be that the later calls delete[] but both are valid..

The first one is NOT valid. The memory MUST be allocated with new, not with new[]. The only reason it compiles at all is because the first syntax expects a double* as input and a double[] degrades into a double*.

I mean how is memory deleted in first case

Using delete, not delete[].

isn't that undefined behavior deleting array with delete?

Yes.

Secondly I know darr above has [] operator defined but how to access 2nd and 3rd member of d since there is no [] operator defined.

You have to use its get() method to access the underlying pointer, eg:

double value = d.get()[1]

Why would anyone use the first syntax rather than the 2nd?

Noone should be being the first syntax for arrays. The second syntax was specifically added for arrays.

Upvotes: 1

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136515

std::unique_ptr:

template <
    class T,
    class Deleter
> class unique_ptr<T[], Deleter>;

Manages the lifetime of a dynamically-allocated array of objects (e.g. allocated with new[]).

Unfortunately, expression std::unique_ptr<double>(new double[3]) compiles with no warnings or errors, ends up disposing the new[] allocation with delete (scalar version) which causes undefined behaviour at run-time.

You can use std::vector<double>(3) to have the array automatically allocated and disposed.

Upvotes: 4

Related Questions