2

I have a function, which filters a vector of pointers, returning the fitered version. By the nature of its parameter, being of type const vector<Data*>&, it can change Data structures, pointed by the pointers. Is there any way to make it unable to change Data through the pointers while still being able to return vector<Data*>, the filtered version of its argument?

Ruslan
  • 18,162
  • 8
  • 67
  • 136
  • You could use some pointer wrapper that will return `const&` to pointee when dereferenced and being `const`. Raw and smart pointers return mutable reference – LogicStuff Dec 19 '15 at 13:40
  • What would you allow in your code to accomplish that? It cannot be done directly. – edmz Dec 19 '15 at 13:40
  • @black the function's parameter can be modified, source of the function also can. Even caller can. It just needs to be more or less straightforward to do (and extensible). – Ruslan Dec 19 '15 at 14:01

1 Answers1

1

You have a unary function taking:

(const vector<Data*>&)

You cannot cast the constness of the pointers inside the vector, but you can change your function's argument type. I suggest this:

(const Data* const*, size_t)

Then, call it like this:

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

Now your function is accepting pointers to const Data so cannot change them. And the caller doesn't need to do anything very special. You could make a wrapper if you want to keep the old calling 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" safety, but then, const never does!

John Zwinck
  • 239,568
  • 38
  • 324
  • 436