如何防止过滤指针的向量与非常量访问指针的函数? [英] How to prevent a function which filters vector of pointers from non-const-accessing pointees?

查看:128
本文介绍了如何防止过滤指针的向量与非常量访问指针的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,它过滤指针的向量,返回fitered版本。通过其参数的属性 const向量,它可以改变 Data 结构,指针指向。是否有任何方法使它无法通过指针更改 Data ,同时仍然能够返回向量< Data *>

解决方案

您有一个一元函数:

 (const向量< Data *>&)


b $ b

您不能在向量内部投射指针的常量,但可以更改函数的参数类型。我建议这样:

 (const Data * const *,size_t)
pre>

然后,这样调用:

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

现在你的函数接受指向 const Data 所以不能改变它们。而调用者不需要做任何非常特别的事情。如果你想保留旧的调用风格,你可以创建一个包装:

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

对于返回类型,可以使用 const_cast

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

这些都没有提供完美安全,但是 const 永远不会!


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?

解决方案

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!

这篇关于如何防止过滤指针的向量与非常量访问指针的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆