TMOTTM
TMOTTM

Reputation: 3381

Why can I not assign values to a shared pointer array?

This small example is giving the error message

Error   C2440   '=': cannot convert from '_Ux (*const )' to 'int *' Templ   1266
Error   C3692   non-scalar type 'int []' cannot be used in a pseudo-destructor expression

What is _Ux(*const)?

This is the program:

#include <memory>
int main()
{
    shared_ptr<int[]> as = make_shared<int[]>(10);
    for (int i = 0; i < 10; i++) {
        as[i] = i + 100;
    }
}

Upvotes: 1

Views: 419

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 595981

The code as shown does not compile, because shared_ptr and make_shared() are in the std namespace, but there is no using namespace std; statement, or at least using std::shared_ptr; and using std::make_shared; statements.

However, fixing that, make sure you are compiling this code for C++20, as std::make_shared() does not support the creation of arrays in earlier versions, which can lead to the error you are seeing.

In C++17, you will have to construct the array manually instead, but std::shared_ptr will free the array correctly, eg:

std::shared_ptr<int[]> as( new int[10] );

Live Demo

But, std::shared_ptr does not support arrays at all in C++11 and C++14, so you will have to use a custom deleter to free the array properly, and use std::shared_ptr::get() instead of std::shared_ptr::operator[] to access the array elements, eg:

#include <memory>

int main()
{
    std::shared_ptr<int> as( new int[10], [](int *p) { delete[] p; } );
    for (int i = 0; i < 10; i++) {
        as.get()[i] = i + 100;
    }
}

For dynamic arrays, you should consider using std::vector instead, eg:

#include <vector>

int main()
{
    std::vector<int> as(10);
    for (int i = 0; i < 10; i++) {
        as[i] = i + 100;
    }
}

Upvotes: 3

Related Questions