Avoiding const_cast when calling std::set<Type*>::find

不想你离开。 提交于 2019-11-30 23:25:12

问题


Is there any good way to obviate the const_cast below, while keeping const correctness?

Without const_cast the code below doesn't compile. set::find gets a const reference to the set's key type, so in our case it guarantees not to change the passed-in pointer value; however, nothing it guaranteed about not changing what the pointer points to.

class C {
public:
   std::set<int*> m_set;

   bool isPtrInSet(const int* ptr) const
   {
       return m_set.find(const_cast<int*>(ptr)) != m_set.end();
   }
};

回答1:


Yes.

In C++14, you can use your own comparator that declares int const* as transparent. This would enable the template overload of find() that can compare keys against arbitrary types. See this related SO question. And here's Jonathan Wakely's explanation.




回答2:


I want to explain the underlying logic of why this is impossible.

Suppose set<int*>::find(const int*) would be legitimate. Then you could do the following:

set<int*> s;
const int* p_const;
// fill s and p
auto it = s.find(p_const);
int* p = *it;

Hey presto! You transformed const int* to int* without performing const_cast.




回答3:


Is there any good way to obviate the const_cast below, while keeping const correctness?

I am not sure whether what I am going to suggest qualifies as a "good way". However, you can avoid the const_cast if you don't mind iterating over the contents of the set yourself. Keep in mind that this transforms what could be an O(log(N)) operation to an O(N) operation.

bool isPtrInSet(const int* ptr) const
{
   for ( auto p : m_set )
   {
      if ( p == ptr )
      {
         return true;
      }
   }
   return false;
}


来源:https://stackoverflow.com/questions/37118000/avoiding-const-cast-when-calling-stdsettypefind

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!