I want to create a std::array
of pointers without declaring the type to which the pointers point to as const
, so that I can change the values pointed to by the pointers of the array through dereference of these pointers.
So I don't want to do this:
#include <array>
int main()
{
int a = 5;
int b = 10;
std::array<const int*, 2> arr = { &a, &b }; // with const
*(arr[0]) = 20; // Because this is not possible.
}
But this:
#include <array>
int main()
{
int a = 5;
int b = 10;
std::array<int*, 2> arr = { &a, &b }; // without const
*(arr[0]) = 20; // Because now it is possible.
}
Now I want to pass this array to a function in such a way that this function can not change the values pointed to by the pointers of the array through dereference of these pointers:
#include <array>
void test(const std::array<int*, 2>& arr)
{
*(arr[0]) = 20; // I want this to not be possible (in this example it is)
}
int main()
{
int a = 5;
int b = 10;
std::array<int*, 2> arr = { &a, &b };
test(arr);
}
How can I do this? Since it is possible with C arrays:
void test(int const * const * const arr)
{
*(arr[0]) = 20; // this is not possible
}
int main()
{
int a = 5;
int b = 10;
int* arr[2] = {&a, &b};
test(arr);
}
I figured it should be possible with C++ std arrays too.
Help much appreciated. Thank you.
std::array
can be transformed to the same pointer, just not implicitly.) – Senttest()
accepting a pointer, not an array. Thetest()
function does not use C-style arrays, so I don't accept it as a demonstration of doing something with C-style arrays. For example, given a suitably-initializedstd::array<int*, 2> stdarr
, you could call the last version oftest
viatest(stdarr.data())
and have no C-style arrays in sight. My point is that the same problem exists for C-style arrays; it's just usually camouflaged by array-to-pointer decay. – Sentconst_view
class that takes in any container and only exposes const access. The will require some code to write all the accessors correctly to get the const to propagate through but shouldn't be to bad. – Xanthein