How to prevent a function that filters a pointer vector from non-const-accessing pointees?

I have a function that filters a vector of pointers, returning a patched version. By the nature of its parameter, which is of type const vector<Data*>& , it can change the Data structures indicated by pointers. Is there a way to make it impossible to change Data through pointers while still having the ability to return vector<Data*> , a filtered version of its argument?

+2
source share
1 answer

You have a unary function:

 (const vector<Data*>&) 

You cannot use the pointer constant inside the vector, but you can change the type of the function argument. I suggest the following:

 (const Data* const*, size_t) 

Then name it like this:

 filter(vec.data(), vec.size()); 

Now your function accepts pointers to const Data , so it cannot change them. And the caller does not need to do anything special. You can create a wrapper if you want to keep the old call style:

 filter(const vector<Data*>& vec) { return filter(vec.data(), vec.size()); } 

As for the return type, you can do it with const_cast :

 vector<Data*> filter(const Data* const* data, size_t size) { vector<Data*> results; for (size_t ii = 0; ii < size; ++ii) { results.push_back(const_cast<Data*>(data[ii])); } return results; } 

None of this provides "perfect" security, but then const never does!

+1
source

Source: https://habr.com/ru/post/1238718/


All Articles